<template>
  <div class="question-bank-management">
    <div class="header">
      <div class="header-top">
        <h1>{{ moduleTitle }}题库管理</h1>
      </div>
      <div class="header-buttons">
        <el-button type="primary" @click="handleAddQuestionClick" v-if="!manualImportOnly">
          <el-icon><Plus /></el-icon>
          添加题目
        </el-button>
        <!-- 手动批量导入按钮 -->
        <el-button type="primary" @click="showManualImportDialog = true">
          <el-icon><DocumentAdd /></el-icon>
          {{ manualImportOnly ? '手动导入题目' : '手动导入' }}
        </el-button>
        <el-button type="danger" :icon="Delete" :disabled="selectedQuestions.length === 0" @click="handleBatchDelete" v-if="!manualImportOnly">批量删除</el-button>
        <el-upload
          class="excel-uploader"
          :http-request="customUpload"
          :headers="{
            'X-Module-Type': moduleType
          }"
          :data="excelUploadData"
          :show-file-list="false"
          accept=".xlsx,.xls"
          :before-upload="beforeExcelUpload"
          :on-success="handleExcelUploadSuccess"
          :on-error="handleExcelUploadError"
          v-if="!manualImportOnly"
        >
          <el-button type="success">
            <el-icon><Upload /></el-icon>
            Excel导入
          </el-button>
        </el-upload>
        <el-button type="success" @click="exportQuestions" v-if="!manualImportOnly">
          <el-icon><Download /></el-icon>
          Excel导出
        </el-button>
        <el-button type="info" @click="downloadTemplate" v-if="!manualImportOnly">
          <el-icon><Download /></el-icon>
          下载模板
        </el-button>
        <el-button type="warning" @click="showTemplateHelp" v-if="!manualImportOnly">
          <el-icon><QuestionFilled /></el-icon>
          模板说明
        </el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar" v-if="!manualImportOnly">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入题目内容或关键词搜索"
        style="width: 300px; margin-right: 10px;"
        clearable
      >
      </el-input>
      <el-select
        v-model="searchDifficulty"
        placeholder="难度筛选"
        style="width: 120px; margin-right: 10px;"
        clearable
      >
        <el-option label="简单" value="easy" />
        <el-option label="中等" value="medium" />
        <el-option label="困难" value="hard" />
      </el-select>
      <el-select
        v-model="searchType"
        placeholder="题型筛选"
        style="width: 120px; margin-right: 10px;"
        clearable
      >
        <el-option label="单选题" value="single_choice" />
        <el-option label="多选题" value="multiple_choice" />
        <el-option label="判断题" value="true_false" />
        <el-option label="填空题" value="fill_blank" />
      </el-select>
      <el-select
        v-if="moduleType === 'wrongQuestion'"
        v-model="searchModule"
        placeholder="模块筛选"
        style="width: 120px; margin-right: 10px;"
        clearable
      >
        <el-option label="时政" value="politics" />
        <el-option label="常识" value="commonSense" />
        <el-option label="言语理解" value="language" />
        <el-option label="判断" value="judgment" />
        <el-option label="数量" value="quantitative" />
        <el-option label="资料分析" value="dataAnalysis" />

      </el-select>
      <!-- 时政模块使用时间筛选 -->
      <el-date-picker
        v-if="moduleType === 'politics'"
        v-model="searchCategory"
        type="date"
        placeholder="时间筛选"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        style="width: 140px; margin-right: 10px;"
        clearable
      />
      <!-- 其他模块使用分类筛选 -->
      <el-select
        v-else
        v-model="searchCategory"
        placeholder="分类筛选"
        style="width: 140px; margin-right: 10px;"
        clearable
      >
        <!-- 常识模块分类 -->
        <template v-if="moduleType === 'commonSense'">
          <el-option label="政治" value="Politics" />
          <el-option label="经济" value="Economics" />
          <el-option label="文史" value="HistoryLiterature" />
          <el-option label="科学与生活" value="ScienceLife" />
          <el-option label="地理" value="Geography" />
          <el-option label="法律" value="Law" />
          <el-option label="管理与公文" value="ManagementDocuments" />
        </template>
        <!-- 言语模块分类 -->
        <template v-else-if="moduleType === 'language'">
          <el-option label="片段阅读" value="SegRead" />
          <el-option label="语句表达" value="SenExp" />
          <el-option label="逻辑填空" value="LogFill" />
        </template>
        <!-- 数量模块分类 -->
        <template v-else-if="moduleType === 'quantitative'">
          <el-option label="倍数特性" value="MulCha" />
          <el-option label="方程问题" value="EquPro" />
          <el-option label="等差数列和等比数列" value="AriGeoSeq" />
          <el-option label="周期问题" value="PerPro" />
          <el-option label="工程问题" value="EngPro" />
          <el-option label="几何问题" value="GeoPro" />
          <el-option label="容斥原理问题" value="IncExcPro" />
          <el-option label="最值问题" value="ExtValPro" />
          <el-option label="年龄问题" value="AgePro" />
          <el-option label="溶液问题" value="SolPro" />
          <el-option label="植树与方程问题" value="PlanEquPro" />
          <el-option label="经济利润问题" value="EcoPro" />
          <el-option label="行程问题" value="TraPro" />
          <el-option label="排列组合问题" value="ComPermPro" />
          <el-option label="数量易拿分小题型" value="EasyNumPro" />
        </template>
        <!-- 判断模块分类 -->
        <template v-else-if="moduleType === 'judgment'">
          <el-option label="图形推理" value="GraRea" />
          <el-option label="定义判断" value="DefRea" />
          <el-option label="类比推理" value="AnaRea" />
          <el-option label="逻辑判断" value="LogRea" />

        </template>
        <!-- 资料模块分类 -->
        <template v-else-if="moduleType === 'dataAnalysis'">
          <el-option label="八大常用速算技巧" value="FastCal" />
          <el-option label="基期量" value="BaseVal" />
          <el-option label="现期量" value="CurrVal" />
          <el-option label="增长率" value="GrowthRt" />
          <el-option label="增长量" value="GrowthAmt" />
          <el-option label="间隔增长率" value="IntvGrowth" />
          <el-option label="乘积增长率" value="ProdGrowth" />
          <el-option label="年均增长率" value="AnnGrowth" />
          <el-option label="混合增长率" value="MixGrowth" />
          <el-option label="比重" value="Proportion" />
          <el-option label="平均数" value="Average" />
          <el-option label="倍数" value="Multiple" />
          <el-option label="A与非A思想" value="ANotA" />
          <el-option label="综合分析" value="CompAnaly" />
        </template>
      </el-select>
      
      <!-- 子分类筛选 -->
      <el-select
        v-if="showSubCategory"
        v-model="searchSubCategory"
        placeholder="子分类筛选"
        style="width: 140px; margin-right: 10px;"
        clearable
      >
        <el-option
          v-for="subCategory in subCategoryOptions"
          :key="subCategory.value"
          :label="subCategory.label"
          :value="subCategory.value"
        />
      </el-select>
      <el-button type="primary" @click="searchQuestions">
        <el-icon><Search /></el-icon>
        搜索
      </el-button>
      <el-button @click="resetSearch">
        <el-icon><Refresh /></el-icon>
        重置
      </el-button>
    </div>

    <!-- 题目列表 -->
    <el-table :data="questionList" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange" v-if="!manualImportOnly">
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column label="序号" width="80">
        <template #default="scope">
          {{ total - (currentPage - 1) * pageSize - scope.$index }}
        </template>
      </el-table-column> -->
      <el-table-column label="ID" width="80">
        <template #default="scope">
          {{ scope.row.questionId || scope.row.id || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="标题" width="150" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.title || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="题目内容" min-width="300" show-overflow-tooltip>
        <template #default="scope">
          <div class="question-content">{{ getTruncatedContent(scope.row.content) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="题型" width="100">
        <template #default="scope">
          <el-tag :type="getTypeTagType(scope.row.questionType || scope.row.type)">
            {{ getTypeText(scope.row.questionType || scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="difficulty" label="难度" width="100" v-if="false">
        <template #default="scope">
          <el-tag :type="getDifficultyTagType(scope.row.difficulty)">
            {{ getDifficultyText(scope.row.difficulty) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="分类" width="100" v-if="['commonSense', 'language', 'quantitative', 'judgment', 'dataAnalysis'].includes(moduleType)">
        <template #default="scope">
          {{ getCategoryText(scope.row.category) }}
        </template>
      </el-table-column>
      <el-table-column label="子分类" width="120" v-if="['commonSense', 'language', 'quantitative', 'judgment', 'dataAnalysis'].includes(moduleType)">
        <template #default="scope">
          {{ getSubCategoryText(scope.row.category, scope.row.subCategory) }}
        </template>
      </el-table-column>
      <el-table-column v-if="moduleType === 'wrongQuestion'" prop="module" label="模块" width="100">
        <template #default="scope">
          {{ getModuleText(scope.row.module) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <div class="action-buttons">
            <el-button size="small" @click="viewQuestion(scope.row)">查看</el-button>
            <el-button size="small" @click="editQuestion(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteQuestion(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination" v-if="!manualImportOnly">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑题目对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="isEdit ? '编辑题目' : '添加题目'"
      width="800px"
      :before-close="handleDialogClose"
    >
      <el-form :model="questionForm" :rules="questionRules" ref="questionFormRef" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="questionForm.title" placeholder="请输入题目标题" />
        </el-form-item>
        <el-form-item label="题目内容" prop="content">
          <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 200px; overflow-y: hidden;"
              v-model="questionForm.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        <el-form-item label="题型" prop="type">
          <el-select v-model="questionForm.type" placeholder="请选择题型" @change="handleTypeChange">
            <el-option label="单选题" value="single_choice" />
            <el-option label="多选题" value="multiple_choice" />
            <el-option label="判断题" value="true_false" />
            <el-option label="填空题" value="fill_blank" />
          </el-select>
        </el-form-item>

        <el-form-item label="难度" prop="difficulty" v-if="false">
          <el-select v-model="questionForm.difficulty" placeholder="请选择难度">
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <!-- 时政模块使用时间选择 -->
          <el-date-picker
            v-if="moduleType === 'politics'"
            v-model="questionForm.category"
            type="date"
            placeholder="请选择时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%;"
          />
          <!-- 其他模块使用分类选择 -->
          <el-select v-else v-model="questionForm.category" placeholder="请选择分类" @change="handleCategoryChange">
            <!-- 常识模块分类 -->
            <template v-if="moduleType === 'commonSense'">
              <el-option label="政治" value="Politics" />
              <el-option label="经济" value="Economics" />
              <el-option label="文史" value="HistoryLiterature" />
              <el-option label="科学与生活" value="ScienceLife" />
              <el-option label="地理" value="Geography" />
              <el-option label="法律" value="Law" />
              <el-option label="管理与公文" value="ManagementDocuments" />
            </template>
            <!-- 言语模块分类 -->
            <template v-else-if="moduleType === 'language'">
              <el-option label="片段阅读" value="SegRead" />
              <el-option label="语句表达" value="SenExp" />
              <el-option label="逻辑填空" value="LogFill" />
            </template>
            <!-- 数量模块分类 -->
            <template v-else-if="moduleType === 'quantitative'">
              <el-option label="倍数特性" value="MulCha" />
              <el-option label="方程问题" value="EquPro" />
              <el-option label="等差数列和等比数列" value="AriGeoSeq" />
              <el-option label="周期问题" value="PerPro" />
              <el-option label="工程问题" value="EngPro" />
              <el-option label="几何问题" value="GeoPro" />
              <el-option label="容斥原理问题" value="IncExcPro" />
              <el-option label="最值问题" value="ExtValPro" />
              <el-option label="年龄问题" value="AgePro" />
              <el-option label="溶液问题" value="SolPro" />
              <el-option label="植树与方程问题" value="PlanEquPro" />
              <el-option label="经济利润问题" value="EcoPro" />
              <el-option label="行程问题" value="TraPro" />
              <el-option label="排列组合问题" value="ComPermPro" />
              <el-option label="数量易拿分小题型" value="EasyNumPro" />
            </template>
            <!-- 判断模块分类 -->
            <template v-else-if="moduleType === 'judgment'">
              <el-option label="图形推理" value="GraRea" />
              <el-option label="定义判断" value="DefRea" />
              <el-option label="类比推理" value="AnaRea" />
              <el-option label="逻辑判断" value="LogRea" />

            </template>
            <!-- 资料模块分类 -->
            <template v-else-if="moduleType === 'dataAnalysis'">
              <el-option label="八大常用速算技巧" value="FastCal" />
              <el-option label="基期量" value="BaseVal" />
              <el-option label="现期量" value="CurrVal" />
              <el-option label="增长率" value="GrowthRt" />
              <el-option label="增长量" value="GrowthAmt" />
              <el-option label="间隔增长率" value="IntvGrowth" />
              <el-option label="乘积增长率" value="ProdGrowth" />
              <el-option label="年均增长率" value="AnnGrowth" />
              <el-option label="混合增长率" value="MixGrowth" />
              <el-option label="比重" value="Proportion" />
              <el-option label="平均数" value="Average" />
              <el-option label="倍数" value="Multiple" />
              <el-option label="A与非A思想" value="ANotA" />
              <el-option label="综合分析" value="CompAnaly" />
            </template>
          </el-select>
        </el-form-item>
        
        <!-- 子分类选择 -->
        <el-form-item 
          v-if="showQuestionSubCategory" 
          label="子分类" 
          prop="subCategory"
        >
          <el-select 
            v-model="questionForm.subCategory" 
            placeholder="请选择子分类"
            clearable
          >
            <el-option
              v-for="subCategory in questionSubCategoryOptions"
              :key="subCategory.value"
              :label="subCategory.label"
              :value="subCategory.value"
            />
          </el-select>
        </el-form-item>

        <!-- 选择题选项 -->
        <div v-if="questionForm.type === 'single_choice' || questionForm.type === 'multiple_choice'">
          <el-form-item label="选项A" prop="optionA">
            <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="optionAEditorRef"
                :defaultConfig="optionToolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 120px; overflow-y: hidden;"
                v-model="questionForm.optionA"
                :defaultConfig="optionEditorConfig"
                :mode="mode"
                @onCreated="handleOptionACreated"
              />
            </div>
          </el-form-item>
          <el-form-item label="选项B" prop="optionB">
            <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="optionBEditorRef"
                :defaultConfig="optionToolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 120px; overflow-y: hidden;"
                v-model="questionForm.optionB"
                :defaultConfig="optionEditorConfig"
                :mode="mode"
                @onCreated="handleOptionBCreated"
              />
            </div>
          </el-form-item>
          <el-form-item label="选项C" prop="optionC">
            <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="optionCEditorRef"
                :defaultConfig="optionToolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 120px; overflow-y: hidden;"
                v-model="questionForm.optionC"
                :defaultConfig="optionEditorConfig"
                :mode="mode"
                @onCreated="handleOptionCCreated"
              />
            </div>
          </el-form-item>
          <el-form-item label="选项D" prop="optionD">
            <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="optionDEditorRef"
                :defaultConfig="optionToolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 120px; overflow-y: hidden;"
                v-model="questionForm.optionD"
                :defaultConfig="optionEditorConfig"
                :mode="mode"
                @onCreated="handleOptionDCreated"
              />
            </div>
          </el-form-item>
        </div>

        <el-form-item label="正确答案" prop="answer">
          <el-input
            v-if="questionForm.type === 'fill'"
            v-model="questionForm.answer"
            placeholder="请输入正确答案"
          />
          <el-select
            v-else-if="questionForm.type === 'true_false'"
            v-model="questionForm.answer"
            placeholder="请选择正确答案"
          >
            <el-option label="正确" value="true" />
            <el-option label="错误" value="false" />
          </el-select>
          <el-checkbox-group
            v-else-if="questionForm.type === 'multiple_choice'"
            v-model="questionForm.answer"
          >
            <el-checkbox label="A">A</el-checkbox>
            <el-checkbox label="B">B</el-checkbox>
            <el-checkbox label="C">C</el-checkbox>
            <el-checkbox label="D">D</el-checkbox>
          </el-checkbox-group>
          <el-radio-group
            v-else
            v-model="questionForm.answer"
          >
            <el-radio label="A">A</el-radio>
            <el-radio label="B">B</el-radio>
            <el-radio label="C">C</el-radio>
            <el-radio label="D">D</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="解析" prop="explanation">
          <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="explanationEditorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 150px; overflow-y: hidden;"
              v-model="questionForm.explanation"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleExplanationCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="saveQuestion">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看题目详情对话框 -->
    <el-dialog
      v-model="showViewDialog"
      title="题目详情"
      width="900px"
      :fullscreen="false"
      :modal="true"
      :append-to-body="true"
      class="question-view-dialog"
    >
      <div v-if="viewQuestionData" class="question-detail">
        <div class="detail-item" v-if="viewQuestionData.title">
          <label>标题：</label>
          <span>{{ viewQuestionData.title }}</span>
        </div>
        <div class="detail-item">
          <label>题目内容：</label>
          <div class="content" v-html="viewQuestionData.content"></div>
        </div>
        
        <div class="detail-item">
          <label>题型：</label>
          <span>{{ getTypeText(viewQuestionData.questionType || viewQuestionData.type) }}</span>
        </div>
        
        <div class="detail-item" v-if="false">
          <label>难度：</label>
          <span>{{ getDifficultyText(viewQuestionData.difficulty) }}</span>
        </div>
        <div class="detail-item" v-if="['commonSense', 'language', 'quantitative', 'judgment', 'dataAnalysis'].includes(moduleType)">
          <label>分类：</label>
          <span>{{ getCategoryText(viewQuestionData.category) }}</span>
        </div>
        
        <div v-if="moduleType === 'politics'" class="detail-item">
          <label>时间：</label>
          <span>{{ viewQuestionData.category || '-' }}</span>
        </div>
        <!-- 添加子分类显示 -->
        <div v-if="viewQuestionData.subCategory && ['commonSense', 'language', 'quantitative', 'judgment', 'dataAnalysis'].includes(moduleType)" class="detail-item">
          <label>子分类：</label>
          <span>{{ getSubCategoryText(viewQuestionData.category, viewQuestionData.subCategory) }}</span>
        </div>
        
        <div v-if="(viewQuestionData.questionType || viewQuestionData.type) === 'single_choice' || (viewQuestionData.questionType || viewQuestionData.type) === 'multiple_choice'" class="detail-item">
          <label>选项：</label>
          <div class="options">
            <div v-if="viewQuestionData.optionA">
              <el-popover
                placement="right"
                :width="400"
                trigger="hover"
                popper-class="option-popover"
                :raw-content="true"
              >
                <template #reference>
                  <span>A. <span v-html="viewQuestionData.optionA"></span></span>
                </template>
                <div class="option-content" v-html="viewQuestionData.optionA"></div>
              </el-popover>
            </div>
            <div v-if="viewQuestionData.optionB">
              <el-popover
                placement="right"
                :width="400"
                trigger="hover"
                popper-class="option-popover"
                :raw-content="true"
              >
                <template #reference>
                  <span>B. <span v-html="viewQuestionData.optionB"></span></span>
                </template>
                <div class="option-content" v-html="viewQuestionData.optionB"></div>
              </el-popover>
            </div>
            <div v-if="viewQuestionData.optionC">
              <el-popover
                placement="right"
                :width="400"
                trigger="hover"
                popper-class="option-popover"
                :raw-content="true"
              >
                <template #reference>
                  <span>C. <span v-html="viewQuestionData.optionC"></span></span>
                </template>
                <div class="option-content" v-html="viewQuestionData.optionC"></div>
              </el-popover>
            </div>
            <div v-if="viewQuestionData.optionD">
              <el-popover
                placement="right"
                :width="400"
                trigger="hover"
                popper-class="option-popover"
                :raw-content="true"
              >
                <template #reference>
                  <span>D. <span v-html="viewQuestionData.optionD"></span></span>
                </template>
                <div class="option-content" v-html="viewQuestionData.optionD"></div>
              </el-popover>
            </div>
          </div>
        </div>
        
        <div class="detail-item">
          <label>正确答案：</label>
          <span class="answer">{{ formatAnswer(viewQuestionData.answer, viewQuestionData.questionType || viewQuestionData.type) }}</span>
        </div>
        
        <div v-if="viewQuestionData.explanation" class="detail-item">
          <label>解析：</label>
          <div class="content">
            <el-tooltip
              effect="light"
              placement="top-start"
              :content="'点击查看完整解析'"
              :enterable="false"
            >
              <el-popover
                placement="right"
                :width="500"
                trigger="click"
                popper-class="explanation-popover"
                :raw-content="true"
              >
                <template #reference>
                  <div class="explanation-preview" v-html="viewQuestionData.explanation"></div>
                </template>
                <div class="explanation-content" v-html="viewQuestionData.explanation"></div>
              </el-popover>
            </el-tooltip>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 手动批量导入对话框 -->
    <el-dialog
      v-model="showManualImportDialog"
      title="手动批量导入题目"
      width="800px"
      class="manual-import-dialog"
    >
      <el-collapse v-model="manualImportActiveNames" style="margin-bottom: 15px;">
        <el-collapse-item name="1">
          <template #title>
            <el-icon style="color: #409eff;"><InfoFilled /></el-icon>
            <span style="margin-left: 8px; color: #409eff; font-weight: 500;">导入格式说明（点击展开）</span>
          </template>
          <div>
            <p><strong>请按照以下格式输入题目内容：</strong></p>
            <p><strong>格式示例：</strong></p>
            <pre style="background-color: #f5f7fa; padding: 10px; border-radius: 4px; overflow-x: auto;">
【例 1】题目内容...
A. 选项A
B. 选项B
C. 选项C
D. 选项D
正确答案：A
解析：解析内容

【例 2】题目内容...
A. 选项A
B. 选项B
C. 选项C
D. 选项D
正确答案：B
解析：解析内容</pre>
            <p><strong>注意事项：</strong></p>
            <ul>
              <li>使用【例 X】作为题目标识，X为题目序号</li>
              <li>题目内容与选项之间不要有空行</li>
              <li>选项格式为大写字母加点，如A. B. C. D.</li>
              <li>正确答案格式为"正确答案：X"，X为选项字母</li>
              <li>解析为可选内容，格式为"解析：解析内容"</li>
              <li>支持批量导入多个题目</li>
              <li>系统会自动移除题目内容中的多余空格</li>
            </ul>
          </div>
        </el-collapse-item>
      </el-collapse>
      
      <el-form>
        <!-- 模块选择 -->
        <el-form-item label="模块选择">
          <el-select v-model="manualImportModuleType" placeholder="请选择模块" @change="handleManualImportModuleChange" style="width: 175px;">
            <el-option label="时政" value="politics" />
            <el-option label="常识" value="commonSense" />
            <el-option label="言语理解" value="language" />
            <el-option label="判断" value="judgment" />
            <el-option label="数量" value="quantitative" />
            <el-option label="资料分析" value="dataAnalysis" />
          </el-select>
        </el-form-item>
        
        <!-- 时政模块使用时间选择器 -->
        <el-form-item label="时间" v-if="manualImportModuleType === 'politics'">
          <el-date-picker
            v-model="manualImportCategory"
            type="date"
            placeholder="请选择时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%;"
          />
        </el-form-item>
        
        <!-- 其他模块使用大分类和小分类输入框 -->
        <template v-else-if="manualImportModuleType">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="大的分类">
                <el-select 
                  v-model="manualImportCategory" 
                  placeholder="请选择大分类" 
                  clearable
                  @change="handleManualImportCategoryChange"
                >
                  <el-option
                    v-for="category in manualImportCategoryOptions"
                    :key="category.value"
                    :label="category.label"
                    :value="category.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="小的分类">
                <el-select 
                  v-model="manualImportSubCategory" 
                  placeholder="请选择小分类" 
                  clearable
                  :disabled="!manualImportCategory"
                >
                  <el-option
                    v-for="subCategory in manualImportSubCategoryOptions"
                    :key="subCategory.value"
                    :label="subCategory.label"
                    :value="subCategory.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        
        <el-form-item label="题目内容">
          <el-input
            v-model="manualImportContent"
            type="textarea"
            :rows="10"
            placeholder="请在此粘贴题目内容，支持批量导入多个题目"
            @input="onManualContentInput"
          />
        </el-form-item>
        
        <div v-if="isFormatValid" class="validation-result valid">
          <el-icon color="#67c23a"><SuccessFilled /></el-icon>
          格式验证通过，共识别到 {{ parsedQuestions.length }} 道题目
        </div>
        
        <div v-if="manualImportContent && !isFormatValid" class="validation-result invalid">
          <el-icon color="#f56c6c"><CircleCloseFilled /></el-icon>
          格式验证未通过，请检查输入内容
        </div>
        
        <div v-if="isFormatValid && parsedQuestions.length > 0" class="question-preview">
          <div class="question-item" v-for="(question, index) in parsedQuestions" :key="index">
            <div class="question-content"><span v-html="`${index + 1}. ${question.content}`"></span></div>
            <div class="question-options">
              <div class="option-item" v-for="(option, key) in question.options" :key="key">
                {{ key }}. {{ option }}
              </div>
            </div>
            <div class="question-answer">正确答案：{{ question.answer }}</div>
          </div>
        </div>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetManualImport">重置</el-button>
          <el-button type="warning" @click="validateManualImportFormat">格式验证</el-button>
          <el-button type="primary" @click="executeManualImport" :disabled="!isFormatValid">批量导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">

import { ref, reactive, onMounted, watch, computed, onBeforeUnmount } from 'vue';
import { Plus, Upload, Download, QuestionFilled, Delete, DocumentAdd, SuccessFilled, CircleCloseFilled, InfoFilled } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';

import { downloadTemplate as downloadTemplateApi, importQuestions, exportQuestions as exportQuestionsApi } from '@/api/questions';
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { modifyQuestionContentImageSizeInHTML } from '@/utils/htmlUtils';
import type { IDomEditor } from '@wangeditor/editor';

import {
  createEditorRef,
  getEditorConfig,
  getOptionEditorConfig,
  getToolbarConfig,
  getOptionToolbarConfig,
  createEditorCallback,
  destroyEditors,
  resetEditorRefs
} from '@/utils/editorUtils';

const beforeExcelUpload = (file: File) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件！');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('文件大小不能超过2MB！');
    return false;
  }
  return true;
};

const handleExcelUploadSuccess = (response: any) => {
  // 这个函数现在不需要做任何事情，因为customUpload函数已经处理了成功提示
  // 避免重复提示
};

const handleExcelUploadError = (error: any) => {
  console.error('Excel上传错误:', error);
  // 不再在这里显示错误信息，避免重复提示
  // 错误信息会在customUpload函数中统一处理
};



const customUpload = async (options: any) => {
  let loadingInstance: any = null;
  
  try {
    // 显示上传进度提示
    loadingInstance = ElLoading.service({
      lock: true,
      text: '正在导入题目，请稍候...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    const formData = new FormData();
    formData.append('file', options.file);
    const response: any = await importQuestions(formData, props.moduleType);
    
    // 关闭加载提示
    if (loadingInstance) {
      loadingInstance.close();
    }
    
    if (response.code === 200) {
      // 构建显示消息，确保包含导入的题目数量
      let message = response.message || '题目导入成功';
      if (response.data !== undefined) {
        // 如果后端返回了具体的数据（导入数量），则在消息中包含它
        if (message === '题目导入成功') {
          // 只有当消息是默认值时，才添加数量信息
          message = `题目导入成功！共导入 ${response.data} 道题目`;
        } else if (!message.includes('共导入')) {
          // 如果消息不是默认值，但也不包含数量信息，则添加数量
          message += `，共导入 ${response.data} 道题目`;
        }
      }
      
      // 直接显示后端返回的详细信息，这是唯一的提示
      ElMessage.success({
        message: message,
        duration: 5000,
        showClose: true
      });
      // 刷新题目列表
      fetchQuestionList();
      options.onSuccess(response);
    } else {
      const error = new Error(response.message || '导入失败');
      options.onError(error);
    }
  } catch (error: any) {
    // 关闭加载提示
    if (loadingInstance) {
      loadingInstance.close();
    }
    
    // 提供更具体的错误信息，确保只显示一条清晰的错误提示
    let errorMessage = '导入失败，请重试';
    if (error.message) {
      // 检查是否是主键冲突错误
      if (error.message.includes('Duplicate entry')) {
        // 提取重复的ID信息
        const duplicateIdMatch = error.message.match(/题目ID ([^ ]+) 已存在/);
        if (duplicateIdMatch && duplicateIdMatch[1]) {
          errorMessage = `导入失败：题目ID ${duplicateIdMatch[1]} 已存在，请检查Excel文件中的ID列，避免重复导入相同ID的题目`;
        } else {
          errorMessage = '导入失败：Excel文件中包含已存在的题目ID，请检查ID列，避免重复导入';
        }
      } else if (error.message.includes('413')) {
        errorMessage = '文件过大，请上传小于2MB的Excel文件';
      } else if (error.message.includes('Network Error')) {
        errorMessage = '网络连接失败，请检查网络后重试';
      } else if (error.message.includes('Excel导入失败')) {
        // 特别处理后端返回的详细错误信息，提取核心错误信息
        const duplicateIdMatch = error.message.match(/Duplicate entry '([^']+)' for key/);
        if (duplicateIdMatch && duplicateIdMatch[1]) {
          errorMessage = `导入失败：题目ID ${duplicateIdMatch[1]} 已存在，请检查Excel文件中的ID列，避免重复导入相同ID的题目`;
        } else {
          errorMessage = '导入失败：Excel文件中包含已存在的题目ID，请检查ID列，避免重复导入';
        }
      } else {
        errorMessage = error.message;
      }
    }
    
    ElMessage.error({
      message: errorMessage,
      duration: 5000,
      showClose: true
    });
    
    // 确保只调用一次onError，避免重复错误提示
    if (options.onError) {
      const simplifiedError = new Error(errorMessage);
      options.onError(simplifiedError);
    }
  }
};

const downloadTemplate = async () => {
  try {
    const response = await downloadTemplateApi();
    const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }));
    const link = document.createElement('a');
    link.href = url;
    link.download = `${props.moduleTitle}题目导入模板.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error('下载模板失败:', error);
    ElMessage.error('下载模板失败，请重试');
  }
};

// 导出题目到Excel
const exportQuestions = async () => {
  let loadingInstance: any = null;
  
  try {
    // 显示导出进度提示
    loadingInstance = ElLoading.service({
      lock: true,
      text: '正在导出题目，请稍候...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    // 获取分类和子分类的中文名称用于导出
    const searchCategoryText = getCategoryText(searchCategory.value);
    const searchSubCategoryText = getSubCategoryText(searchCategory.value, searchSubCategory.value);
    
    const params = {
      keyword: searchKeyword.value || undefined,
      difficulty: searchDifficulty.value || undefined,
      questionType: searchType.value || undefined,
      module: props.moduleType === 'wrongQuestion' ? searchModule.value : props.moduleType,
      category: searchCategory.value ? searchCategoryText : undefined,
      subCategory: searchSubCategory.value ? searchSubCategoryText : undefined,
      orderBy: 'id',
      orderType: 'asc'
    };

    const response = await exportQuestionsApi(params);
    
    // 关闭加载提示
    if (loadingInstance) {
      loadingInstance.close();
    }
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }));
    const link = document.createElement('a');
    link.href = url;
    link.download = `${props.moduleTitle}题目导出.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success({
      message: '题目导出成功！文件已开始下载',
      duration: 5000,
      showClose: true
    });
  } catch (error: any) {
    // 关闭加载提示
    if (loadingInstance) {
      loadingInstance.close();
    }
    
    console.error('导出失败:', error);
    
    let errorMessage = '导出失败，请重试';
    if (error.message) {
      if (error.message.includes('Network Error')) {
        errorMessage = '网络连接失败，请检查网络后重试';
      } else {
        errorMessage = error.message;
      }
    }
    
    ElMessage.error({
      message: errorMessage,
      duration: 5000,
      showClose: true
    });
  }
};

const showTemplateHelp = () => {
  ElMessageBox.alert(
    `<div class="template-help">
      <h3>Excel题目导入模板说明</h3>
      <h4>模板格式说明</h4>
      <p>模板包含以下列：</p>
      <ol>
        <li><strong>ID（选填）</strong>：题目的唯一标识符，导入时可留空，系统会自动生成</li>
        <li><strong>标题（选填）</strong>：题目的标题</li>
        <li><strong>题目内容（必填）</strong>：题目的具体内容</li>
        <li><strong>题型（必填）</strong>：可选值为
          <ul>
            <li>single：单选题</li>
            <li>multiple：多选题</li>
            <li>judge：判断题</li>
            <li>fill：填空题</li>
          </ul>
        </li>
        <li><strong>难度（必填）</strong>：可选值为
          <ul>
            <li>easy：简单</li>
            <li>medium：中等</li>
            <li>hard：困难</li>
          </ul>
        </li>
        <li><strong>选项A-D</strong>：选择题必填</li>
        <li><strong>正确答案（选填）</strong>：

          <ul>
            <li>单选题：填写A、B、C、D</li>
            <li>多选题：多个选项用英文逗号分隔，如"A,B,D"</li>
            <li>判断题：填写true或false</li>
            <li>填空题：填写正确答案文本</li>
          </ul>
        </li>
        <li><strong>解析（选填）</strong>：题目的解析说明</li>
        <li><strong>分类（选填）</strong>：题目的分类信息</li>
        <li><strong>子分类（选填）</strong>：题目的子分类信息</li>
      </ol>
      <h4>注意事项</h4>
      <ul>
        <li>第一行为表头，请勿修改或删除</li>
        <li>所有必填项不能为空</li>
        <li>选择题必须填写完整的选项A、B、C、D</li>
        <li>文件大小不能超过2MB</li>
        <li>仅支持.xlsx或.xls格式的Excel文件</li>
        <li>导出的Excel文件包含分类和子分类字段，可用于批量导入时设置题目的分类信息</li>
      </ul>
    </div>`,
    '模板填写说明',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '知道了',
      customClass: 'template-help-dialog'
    }
  );
};


// Props
interface Props {
  moduleType: string; // 模块类型：politics, commonSense, language, quantity, judgment, dataAnalysis
  moduleTitle: string; // 模块标题
  apiModule: any; // API模块
  manualImportOnly?: boolean; // 是否仅显示手动导入功能
}

const props = defineProps<Props>();

// 设置默认值
const manualImportOnly = computed(() => props.manualImportOnly || false);

// 富文本编辑器配置
const editorRef = createEditorRef();
const optionAEditorRef = createEditorRef();
const optionBEditorRef = createEditorRef();
const optionCEditorRef = createEditorRef();
const optionDEditorRef = createEditorRef();
const explanationEditorRef = createEditorRef();
const mode = 'default';

// 图片上传配置已移至 editorUtils.ts 模块

// 使用从 @/utils/htmlUtils 导入的 modifyQuestionContentImageSizeInHTML 函数

// 获取模块显示名称
const getModuleDisplayName = () => {
  const moduleMap: Record<string, string> = {
    politics: '时政题目',
    commonSense: '常识题目',
    language: '言语理解题目',
    quantity: '数量题目',
    judgment: '判断题目',
    dataAnalysis: '资料分析题目',
    wrongQuestion: '错题题目'
  };
  return moduleMap[props.moduleType] || `${props.moduleTitle}题目`;
};

// 编辑器配置
const editorConfig = getEditorConfig('请输入题目内容...', getModuleDisplayName());
const optionEditorConfig = getOptionEditorConfig(undefined, getModuleDisplayName());

// 工具栏配置
const toolbarConfig = getToolbarConfig();
const optionToolbarConfig = getOptionToolbarConfig();

// 编辑器创建回调
const handleCreated = createEditorCallback(editorRef);
const handleOptionACreated = createEditorCallback(optionAEditorRef);
const handleOptionBCreated = createEditorCallback(optionBEditorRef);
const handleOptionCCreated = createEditorCallback(optionCEditorRef);
const handleOptionDCreated = createEditorCallback(optionDEditorRef);
const handleExplanationCreated = createEditorCallback(explanationEditorRef);

// 响应式数据
const loading = ref(false);
const questionList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const selectedQuestions = ref<any[]>([]);
const searchKeyword = ref('');
const searchDifficulty = ref('');
const searchType = ref('');
const searchCategory = ref('');
const searchSubCategory = ref(''); // 添加子分类搜索
const showAddDialog = ref(false);
const showViewDialog = ref(false);
const isEdit = ref(false);
const questionFormRef = ref<any>(null);
// 手动批量导入相关数据
const showManualImportDialog = ref(false);
const manualImportContent = ref('');
const manualImportModuleType = ref(''); // 添加模块类型字段
const manualImportCategory = ref(''); // 添加大分类字段
const manualImportSubCategory = ref(''); // 添加小分类字段
const isFormatValid = ref(false);
const parsedQuestions = ref<any[]>([]);
const manualImportActiveNames = ref([]); // 默认不展开格式说明
let manualImportContentInputTimer: any = null;

// 手动导入分类选项
const manualImportCategoryOptions = computed(() => {
  const categories: Record<string, Array<{ label: string; value: string }>> = {
    // 常识模块分类
    commonSense: [
      { label: '政治', value: 'Politics' },
      { label: '经济', value: 'Economics' },
      { label: '文史', value: 'HistoryLiterature' },
      { label: '科学与生活', value: 'ScienceLife' },
      { label: '地理', value: 'Geography' },
      { label: '法律', value: 'Law' },
      { label: '管理与公文', value: 'ManagementDocuments' }
    ],
    // 言语模块分类
    language: [
      { label: '片段阅读', value: 'SegRead' },
      { label: '语句表达', value: 'SenExp' },
      { label: '逻辑填空', value: 'LogFill' }
    ],
    // 数量模块分类
    quantitative: [
      { label: '倍数特性', value: 'MulCha' },
      { label: '方程问题', value: 'EquPro' },
      { label: '等差数列和等比数列', value: 'AriGeoSeq' },
      { label: '周期问题', value: 'PerPro' },
      { label: '工程问题', value: 'EngPro' },
      { label: '几何问题', value: 'GeoPro' },
      { label: '容斥原理问题', value: 'IncExcPro' },
      { label: '最值问题', value: 'ExtValPro' },
      { label: '年龄问题', value: 'AgePro' },
      { label: '溶液问题', value: 'SolPro' },
      { label: '植树与方程问题', value: 'PlanEquPro' },
      { label: '经济利润问题', value: 'EcoPro' },
      { label: '行程问题', value: 'TraPro' },
      { label: '排列组合问题', value: 'ComPermPro' },
      { label: '数量易拿分小题型', value: 'EasyNumPro' }
    ],
    // 判断模块分类
    judgment: [
      { label: '图形推理', value: 'GraRea' },
      { label: '定义判断', value: 'DefRea' },
      { label: '类比推理', value: 'AnaRea' },
      { label: '逻辑判断', value: 'LogRea' }
    ],
    // 资料模块分类
    dataAnalysis: [
      { label: '八大常用速算技巧', value: 'FastCal' },
      { label: '基期量', value: 'BaseVal' },
      { label: '现期量', value: 'CurrVal' },
      { label: '增长率', value: 'GrowthRt' },
      { label: '增长量', value: 'GrowthAmt' },
      { label: '间隔增长率', value: 'IntvGrowth' },
      { label: '乘积增长率', value: 'ProdGrowth' },
      { label: '年均增长率', value: 'AnnGrowth' },
      { label: '混合增长率', value: 'MixGrowth' },
      { label: '比重', value: 'Proportion' },
      { label: '平均数', value: 'Average' },
      { label: '倍数', value: 'Multiple' },
      { label: 'A与非A思想', value: 'ANotA' },
      { label: '综合分析', value: 'CompAnaly' }
    ]
  };
  
  return categories[manualImportModuleType.value] || [];
});

const manualImportSubCategoryOptions = computed(() => {
  // 根据主分类返回相应的子分类选项
  const subCategories: Record<string, Array<{ label: string; value: string }>> = {
    // 常识模块子分类
    Politics: [
      { label: '时事政治', value: 'CurrentPolitics' },
      { label: '政策解读', value: 'PolicyInterpretation' },
      { label: '政治理论', value: 'PoliticalTheory' }
    ],
    Economics: [
      { label: '宏观经济', value: 'MacroEconomics' },
      { label: '微观经济', value: 'MicroEconomics' },
      { label: '经济政策', value: 'EconomicPolicy' }
    ],
    HistoryLiterature: [
      { label: '中国历史', value: 'ChineseHistory' },
      { label: '世界历史', value: 'WorldHistory' },
      { label: '文学常识', value: 'LiteraryKnowledge' }
    ],
    ScienceLife: [
      { label: '自然科学', value: 'NaturalScience' },
      { label: '生活常识', value: 'LifeCommonSense' },
      { label: '科技前沿', value: 'TechnologyFrontier' }
    ],
    Geography: [
      { label: '自然地理', value: 'PhysicalGeography' },
      { label: '人文地理', value: 'HumanGeography' },
      { label: '地理常识', value: 'GeographicalKnowledge' }
    ],
    Law: [
      { label: '宪法法律', value: 'ConstitutionalLaw' },
      { label: '行政法', value: 'AdministrativeLaw' },
      { label: '民法', value: 'CivilLaw' }
    ],
    ManagementDocuments: [
      { label: '管理学', value: 'Management' },
      { label: '公文写作', value: 'OfficialDocumentWriting' },
      { label: '行政管理', value: 'AdministrativeManagement' }
    ],
    // 言语模块子分类
    SegRead: [
      { label: '中心理解题', value: 'CentralComprehension' },
      { label: '细节判断题', value: 'DetailJudgment' }
    ],
    SenExp: [
      { label: '接语选择题', value: 'DiscourseSelection' },
      { label: '语句填空题', value: 'SentenceFilling' },
      { label: '语句排序题', value: 'SentenceOrdering' }
    ],
    LogFill: [
      { label: '词的辨析', value: 'WordAnalysis' },
      { label: '语境分析', value: 'ContextualAnalysis' }
    ],
    // 数量模块子分类
    MulCha: [
      { label: '奇偶性', value: 'Parity' },
      { label: '整除特性', value: 'Divisibility' },
      { label: '比例倍数', value: 'RatioMultiple' }
    ],
    EquPro: [
      { label: '一元一次方程', value: 'LinearEquation' },
      { label: '二元一次方程', value: 'BinaryLinearEquation' },
      { label: '不定方程', value: 'IndeterminateEquation' }
    ],
    // 判断模块子分类
    DefRea: [
      { label: '定义推理', value: 'DefinitionReasoning' },
      { label: '概念分析', value: 'ConceptAnalysis' }
    ],
    AnaRea: [
      { label: '类比推理', value: 'AnalogyReasoning' },
      { label: '关系分析', value: 'RelationshipAnalysis' }
    ],
    LogRea: [
      { label: '逻辑推理', value: 'LogicalReasoning' },
      { label: '命题逻辑', value: 'PropositionalLogic' }
    ],
    GraRea: [
      { label: '图形推理', value: 'GraphicReasoning' },
      { label: '模式识别', value: 'PatternRecognition' }
    ],
    // 资料模块子分类
    FastCal: [
      { label: '快速计算', value: 'QuickCalculation' },
      { label: '估算技巧', value: 'Estimation' }
    ],
    BaseVal: [
      { label: '基期计算', value: 'BasePeriod' },
      { label: '基期增长', value: 'BaseGrowth' }
    ],
    CurrVal: [
      { label: '现期计算', value: 'CurrentPeriod' },
      { label: '现期增长', value: 'CurrentGrowth' }
    ],
    GrowthRt: [
      { label: '增长率计算', value: 'GrowthRate' },
      { label: '同比计算', value: 'YearOnYear' }
    ],
    GrowthAmt: [
      { label: '增长量计算', value: 'GrowthAmount' },
      { label: '绝对变化', value: 'AbsoluteChange' }
    ],
    IntvGrowth: [
      { label: '间隔增长率', value: 'IntervalGrowth' },
      { label: '多期计算', value: 'MultiPeriod' }
    ],
    ProdGrowth: [
      { label: '乘积增长率', value: 'ProductGrowth' },
      { label: '复合增长率', value: 'CompoundGrowth' }
    ],
    AnnGrowth: [
      { label: '年均增长率', value: 'AnnualGrowth' },
      { label: '平均增长率', value: 'AverageGrowth' }
    ],
    MixGrowth: [
      { label: '混合增长率', value: 'MixedGrowth' },
      { label: '综合增长率', value: 'CompositeGrowth' }
    ],
    Proportion: [
      { label: '权重计算', value: 'Weight' },
      { label: '份额计算', value: 'Share' }
    ],
    Average: [
      { label: '平均数计算', value: 'Mean' },
      { label: '加权平均', value: 'WeightedAverage' }
    ],
    Multiple: [
      { label: '倍数计算', value: 'Ratio' },
      { label: '比例关系', value: 'Proportionality' }
    ],
    ANotA: [
      { label: '补集思想', value: 'Complement' },
      { label: '差集思想', value: 'Difference' }
    ],
    CompAnaly: [
      { label: '综合分析', value: 'Comprehensive' },
      { label: '数据解读', value: 'DataInterpretation' }
    ]
  };
  
  return subCategories[manualImportCategory.value] || [];
});

// 子分类相关数据
const showSubCategory = computed(() => {
  // 在这里定义哪些模块需要显示子分类
  // 修改为包含所有支持分类的模块
  return ['politics', 'commonSense', 'language', 'quantitative', 'judgment', 'dataAnalysis'].includes(props.moduleType);
});

const subCategoryOptions = computed(() => {
  // 根据主分类返回相应的子分类选项
  const subCategories: Record<string, Array<{ label: string; value: string }>> = {
    // 常识模块子分类
    Politics: [
      { label: '时事政治', value: 'CurrentPolitics' },
      { label: '政策解读', value: 'PolicyInterpretation' },
      { label: '政治理论', value: 'PoliticalTheory' }
    ],
    Economics: [
      { label: '宏观经济', value: 'MacroEconomics' },
      { label: '微观经济', value: 'MicroEconomics' },
      { label: '经济政策', value: 'EconomicPolicy' }
    ],
    HistoryLiterature: [
      { label: '中国历史', value: 'ChineseHistory' },
      { label: '世界历史', value: 'WorldHistory' },
      { label: '文学常识', value: 'LiteraryKnowledge' }
    ],
    ScienceLife: [
      { label: '自然科学', value: 'NaturalScience' },
      { label: '生活常识', value: 'LifeCommonSense' },
      { label: '科技前沿', value: 'TechnologyFrontier' }
    ],
    Geography: [
      { label: '自然地理', value: 'PhysicalGeography' },
      { label: '人文地理', value: 'HumanGeography' },
      { label: '地理常识', value: 'GeographicalKnowledge' }
    ],
    Law: [
      { label: '宪法法律', value: 'ConstitutionalLaw' },
      { label: '行政法', value: 'AdministrativeLaw' },
      { label: '民法', value: 'CivilLaw' }
    ],
    ManagementDocuments: [
      { label: '管理学', value: 'Management' },
      { label: '公文写作', value: 'OfficialDocumentWriting' },
      { label: '行政管理', value: 'AdministrativeManagement' }
    ],
    // 言语模块子分类
    SegRead: [
      { label: '中心理解题', value: 'CentralComprehension' },
      { label: '细节判断题', value: 'DetailJudgment' }
    ],
    SenExp: [
      { label: '接语选择题', value: 'DiscourseSelection' },
      { label: '语句填空题', value: 'SentenceFilling' },
      { label: '语句排序题', value: 'SentenceOrdering' }
    ],
    LogFill: [
      { label: '词的辨析', value: 'WordAnalysis' },
      { label: '语境分析', value: 'ContextualAnalysis' }
    ],
    // 数量模块子分类
    MulCha: [
      { label: '奇偶性', value: 'Parity' },
      { label: '整除特性', value: 'Divisibility' },
      { label: '比例倍数', value: 'RatioMultiple' }
    ],
    EquPro: [
      { label: '一元一次方程', value: 'LinearEquation' },
      { label: '二元一次方程', value: 'BinaryLinearEquation' },
      { label: '不定方程', value: 'IndeterminateEquation' }
    ],
    // 判断模块子分类
    DefRea: [
      { label: '定义推理', value: 'DefinitionReasoning' },
      { label: '概念分析', value: 'ConceptAnalysis' }
    ],
    AnaRea: [
      { label: '类比推理', value: 'AnalogyReasoning' },
      { label: '关系分析', value: 'RelationshipAnalysis' }
    ],
    LogRea: [
      { label: '逻辑推理', value: 'LogicalReasoning' },
      { label: '命题逻辑', value: 'PropositionalLogic' }
    ],
    GraRea: [
      { label: '图形推理', value: 'GraphicReasoning' },
      { label: '模式识别', value: 'PatternRecognition' }
    ],
    // 资料模块子分类
    FastCal: [
      { label: '快速计算', value: 'QuickCalculation' },
      { label: '估算技巧', value: 'Estimation' }
    ],
    BaseVal: [
      { label: '基期计算', value: 'BasePeriod' },
      { label: '基期增长', value: 'BaseGrowth' }
    ],
    CurrVal: [
      { label: '现期计算', value: 'CurrentPeriod' },
      { label: '现期增长', value: 'CurrentGrowth' }
    ],
    GrowthRt: [
      { label: '增长率计算', value: 'GrowthRate' },
      { label: '同比计算', value: 'YearOnYear' }
    ],
    GrowthAmt: [
      { label: '增长量计算', value: 'GrowthAmount' },
      { label: '绝对变化', value: 'AbsoluteChange' }
    ],
    IntvGrowth: [
      { label: '间隔增长率', value: 'IntervalGrowth' },
      { label: '多期计算', value: 'MultiPeriod' }
    ],
    ProdGrowth: [
      { label: '乘积增长率', value: 'ProductGrowth' },
      { label: '复合增长率', value: 'CompoundGrowth' }
    ],
    AnnGrowth: [
      { label: '年均增长率', value: 'AnnualGrowth' },
      { label: '平均增长率', value: 'AverageGrowth' }
    ],
    MixGrowth: [
      { label: '混合增长率', value: 'MixedGrowth' },
      { label: '综合增长率', value: 'CompositeGrowth' }
    ],
    Proportion: [
      { label: '权重计算', value: 'Weight' },
      { label: '份额计算', value: 'Share' }
    ],
    Average: [
      { label: '平均数计算', value: 'Mean' },
      { label: '加权平均', value: 'WeightedAverage' }
    ],
    Multiple: [
      { label: '倍数计算', value: 'Ratio' },
      { label: '比例关系', value: 'Proportionality' }
    ],
    ANotA: [
      { label: '补集思想', value: 'Complement' },
      { label: '差集思想', value: 'Difference' }
    ],
    CompAnaly: [
      { label: '综合分析', value: 'Comprehensive' },
      { label: '数据解读', value: 'DataInterpretation' }
    ]
  };
  
  return subCategories[searchCategory.value] || [];
});

// 添加题目表单中的子分类相关计算属性
const showQuestionSubCategory = computed(() => {
  // 在题目表单中显示子分类的条件
  // 修改为包含所有支持分类的模块
  return ['politics', 'commonSense', 'language', 'quantitative', 'judgment', 'dataAnalysis'].includes(props.moduleType) 
    && !!questionForm.category;
});

// Excel上传数据
const excelUploadData = computed(() => {
  const data: Record<string, any> = {};
  // 只有当时政模块时才添加category和subCategory
  // 对于其他模块，category和subCategory是分类和子分类
  if (searchCategory.value) {
    data.category = searchCategory.value;
  }
  if (searchSubCategory.value) {
    data.subCategory = searchSubCategory.value;
  }
  return data;
});

const questionSubCategoryOptions = computed(() => {
  // 根据题目表单中的主分类返回相应的子分类选项
  const subCategories: Record<string, Array<{ label: string; value: string }>> = {
    // 常识模块子分类
    Politics: [
      { label: '时事政治', value: 'CurrentPolitics' },
      { label: '政策解读', value: 'PolicyInterpretation' },
      { label: '政治理论', value: 'PoliticalTheory' }
    ],
    Economics: [
      { label: '宏观经济', value: 'MacroEconomics' },
      { label: '微观经济', value: 'MicroEconomics' },
      { label: '经济政策', value: 'EconomicPolicy' }
    ],
    HistoryLiterature: [
      { label: '中国历史', value: 'ChineseHistory' },
      { label: '世界历史', value: 'WorldHistory' },
      { label: '文学常识', value: 'LiteraryKnowledge' }
    ],
    ScienceLife: [
      { label: '自然科学', value: 'NaturalScience' },
      { label: '生活常识', value: 'LifeCommonSense' },
      { label: '科技前沿', value: 'TechnologyFrontier' }
    ],
    Geography: [
      { label: '自然地理', value: 'PhysicalGeography' },
      { label: '人文地理', value: 'HumanGeography' },
      { label: '地理常识', value: 'GeographicalKnowledge' }
    ],
    Law: [
      { label: '宪法法律', value: 'ConstitutionalLaw' },
      { label: '行政法', value: 'AdministrativeLaw' },
      { label: '民法', value: 'CivilLaw' }
    ],
    ManagementDocuments: [
      { label: '管理学', value: 'Management' },
      { label: '公文写作', value: 'OfficialDocumentWriting' },
      { label: '行政管理', value: 'AdministrativeManagement' }
    ],
    // 言语模块子分类
    SegRead: [
      { label: '中心理解题', value: 'CentralComprehension' },
      { label: '细节判断题', value: 'DetailJudgment' }
    ],
    SenExp: [
      { label: '接语选择题', value: 'DiscourseSelection' },
      { label: '语句填空题', value: 'SentenceFilling' },
      { label: '语句排序题', value: 'SentenceOrdering' }
    ],
    LogFill: [
      { label: '词的辨析', value: 'WordAnalysis' },
      { label: '语境分析', value: 'ContextualAnalysis' }
    ],
    // 数量模块子分类
    MulCha: [
      { label: '奇偶性', value: 'Parity' },
      { label: '整除特性', value: 'Divisibility' },
      { label: '比例倍数', value: 'RatioMultiple' }
    ],
    EquPro: [
      { label: '一元一次方程', value: 'LinearEquation' },
      { label: '二元一次方程', value: 'BinaryLinearEquation' },
      { label: '不定方程', value: 'IndeterminateEquation' }
    ],
    // 判断模块子分类
    DefRea: [
      { label: '定义推理', value: 'DefinitionReasoning' },
      { label: '概念分析', value: 'ConceptAnalysis' }
    ],
    AnaRea: [
      { label: '类比推理', value: 'AnalogyReasoning' },
      { label: '关系分析', value: 'RelationshipAnalysis' }
    ],
    LogRea: [
      { label: '逻辑推理', value: 'LogicalReasoning' },
      { label: '命题逻辑', value: 'PropositionalLogic' }
    ],
    GraRea: [
      { label: '图形推理', value: 'GraphicReasoning' },
      { label: '模式识别', value: 'PatternRecognition' }
    ],
    // 资料模块子分类
    FastCal: [
      { label: '快速计算', value: 'QuickCalculation' },
      { label: '估算技巧', value: 'Estimation' }
    ],
    BaseVal: [
      { label: '基期计算', value: 'BasePeriod' },
      { label: '基期增长', value: 'BaseGrowth' }
    ],
    CurrVal: [
      { label: '现期计算', value: 'CurrentPeriod' },
      { label: '现期增长', value: 'CurrentGrowth' }
    ],
    GrowthRt: [
      { label: '增长率计算', value: 'GrowthRate' },
      { label: '同比计算', value: 'YearOnYear' }
    ],
    GrowthAmt: [
      { label: '增长量计算', value: 'GrowthAmount' },
      { label: '绝对变化', value: 'AbsoluteChange' }
    ],
    IntvGrowth: [
      { label: '间隔增长率', value: 'IntervalGrowth' },
      { label: '多期计算', value: 'MultiPeriod' }
    ],
    ProdGrowth: [
      { label: '乘积增长率', value: 'ProductGrowth' },
      { label: '复合增长率', value: 'CompoundGrowth' }
    ],
    AnnGrowth: [
      { label: '年均增长率', value: 'AnnualGrowth' },
      { label: '平均增长率', value: 'AverageGrowth' }
    ],
    MixGrowth: [
      { label: '混合增长率', value: 'MixedGrowth' },
      { label: '综合增长率', value: 'CompositeGrowth' }
    ],
    Proportion: [
      { label: '权重计算', value: 'Weight' },
      { label: '份额计算', value: 'Share' }
    ],
    Average: [
      { label: '平均数计算', value: 'Mean' },
      { label: '加权平均', value: 'WeightedAverage' }
    ],
    Multiple: [
      { label: '倍数计算', value: 'Ratio' },
      { label: '比例关系', value: 'Proportionality' }
    ],
    ANotA: [
      { label: '补集思想', value: 'Complement' },
      { label: '差集思想', value: 'Difference' }
    ],
    CompAnaly: [
      { label: '综合分析', value: 'Comprehensive' },
      { label: '数据解读', value: 'DataInterpretation' }
    ]
  };
  
  return subCategories[questionForm.category] || [];
});

// 查看题目详情相关数据
const viewQuestionData = ref<any>(null);

// 定义题目表单接口
interface QuestionForm {
  id: number | null;
  title: string;
  content: string;
  type: string;
  difficulty: string;
  category: string;
  subCategory: string; // 添加子分类字段
  optionA: string;
  optionB: string;
  optionC: string;
  optionD: string;
  answer: string | string[];
  explanation: string;
}

// 题目表单数据
const questionForm = reactive<QuestionForm>({
  id: null,
  title: '',
  content: '',
  type: '', // 默认题型为空，强制用户选择
  difficulty: 'easy',
  category: '', // 分类字段
  subCategory: '', // 子分类字段
  optionA: '',
  optionB: '',
  optionC: '',
  optionD: '',
  answer: '',
  explanation: ''
});

// 表单验证规则
// 选项验证器
const validateOption = (rule: any, value: any, callback: any) => {
  if (questionForm.type === 'single_choice' || questionForm.type === 'multiple_choice') {
    if (!value) {
      callback(new Error('请输入选项内容'));
    } else {
      callback();
    }
  } else {
    callback();
  }
};

const questionRules = {
  title: [
    { required: false, message: '请输入题目标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入题目内容', trigger: 'blur' },
    { min: 10, message: '题目内容至少10个字符', trigger: 'blur' }
  ],  type: [
    { required: true, message: '请选择题型', trigger: ['change', 'blur'] }
  ],
  difficulty: [
    { required: true, message: '请选择难度', trigger: ['change', 'blur'] }
  ],
  category: [
    { 
      required: true, 
      validator: (rule: any, value: any, callback: any) => {
        if (props.moduleType === 'politics') {
          if (!value) {
            callback(new Error('请选择时间'));
          } else {
            callback();
          }
        } else {
          if (!value) {
            callback(new Error('请选择分类'));
          } else {
            callback();
          }
        }
      },
      trigger: ['change', 'blur'] 
    }
  ],
  subCategory: [
    {
      required: false, // 子分类不是必填项
      validator: (rule: any, value: any, callback: any) => {
        // 如果需要子分类验证逻辑，可以在这里添加
        callback();
      },
      trigger: ['change', 'blur']
    }
  ],
  answer: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (questionForm.type === 'single_choice' || questionForm.type === 'multiple_choice' || questionForm.type === 'true_false' || questionForm.type === 'fill_blank') {
          if (questionForm.type === 'multiple_choice') {
            if (!value || value.length === 0) {
              callback(new Error('请设置正确答案'));
            } else {
              callback();
            }
          } else {
            if (!value) {
              callback(new Error('请设置正确答案'));
            } else {
              callback();
            }
          }
        } else {
          callback(); // 其他题型不强制要求答案
        }
      },
      trigger: 'blur'
    }
  ],
  optionA: [
    { validator: validateOption, trigger: 'blur' }
  ],
  optionB: [
    { validator: validateOption, trigger: 'blur' }
  ],
  optionC: [
    { validator: validateOption, trigger: 'blur' }
  ],
  optionD: [
    { validator: validateOption, trigger: 'blur' }
  ]
};

// 修改searchQuestions函数
const searchQuestions = () => {
  currentPage.value = 1;
  fetchQuestionList();
};

// 修改resetSearch函数
const resetSearch = () => {
  searchKeyword.value = '';
  searchDifficulty.value = '';
  searchType.value = '';
  searchModule.value = '';
  searchCategory.value = '';
  searchSubCategory.value = ''; // 重置子分类搜索
  searchQuestions();
};

// 获取题目列表
const fetchQuestionList = async () => {
  loading.value = true;
  try {
    // 获取分类和子分类的中文名称用于搜索
    const searchCategoryText = getCategoryText(searchCategory.value);
    const searchSubCategoryText = getSubCategoryText(searchCategory.value, searchSubCategory.value);
    
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value || undefined,
      difficulty: searchDifficulty.value || undefined,
      questionType: searchType.value || undefined,
      module: props.moduleType === 'wrongQuestion' ? searchModule.value : props.moduleType,
      category: searchCategory.value ? searchCategoryText : undefined,
      subCategory: searchSubCategory.value ? searchSubCategoryText : undefined, // 添加子分类参数
      orderBy: 'question_id',
      orderType: 'asc'
    };

    const response: any = await props.apiModule.getQuestions(params);
    if (response.code === 200) {
      // 处理返回的题目数据
      questionList.value = response.data.questions.map((question: any) => {
        const processedQuestion = {
          ...question,
          id: question.id || question.questionId, // 确保id字段存在
          questionType: question.questionType, // 保留原始questionType字段
          type: question.questionType,
          content: question.content,
          // 处理选项数据
          ...(question.options && typeof question.options === 'string' ? JSON.parse(question.options) : {}),
          answer: question.correctAnswer || question.answer,
          module: (() => {
            const moduleMap: { [key: string]: string } = {
              '时政': 'politics',
              '常识': 'commonSense',
              '言语理解': 'language',
              '判断': 'judgment',
              '数量': 'quantitative',
              '资料分析': 'dataAnalysis'
            };
            return moduleMap[question.module] || question.module; // 如果有映射则转换，否则保持原样
          })() // 添加module字段并进行中文到英文的映射
        };


        return processedQuestion;
      });
      total.value = response.data.total;
    } else {
      ElMessage.error(response.message || '获取题目列表失败');
    }
  } catch (error) {
    console.error('获取题目列表失败:', error);
    ElMessage.error('获取题目列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索题目
const searchModule = ref('');

// 查看题目详情
const viewQuestion = async (question: any) => {
  // 检查题目对象的有效性
  if (!question) {
    ElMessage.error('题目对象无效');
    return;
  }

  // 获取题目ID，优先使用 questionId，其次使用 id
  const questionId = question.questionId || question.id;

  // 检查ID的有效性
  if (!questionId || isNaN(Number(questionId))) {
    ElMessage.error('题目ID无效，无法查看详情');
    console.error('无效的题目ID:', questionId);
    return;
  }

  try {
    // 确保传递给API的ID是数字类型
    const numericQuestionId = Number(questionId);
    const response: any = await props.apiModule.getQuestion(numericQuestionId);
    if (response.code === 200) {
      const questionData = response.data;
      
      // 处理选项数据
      let options: Record<string, string> = {};
      if (questionData.options && typeof questionData.options === 'string') {
        try {
          options = JSON.parse(questionData.options);
        } catch (e) {
          console.error('解析选项数据失败:', e);
        }
      }
      
      // 创建一个新对象来存储处理后的题目数据，避免影响原始数据
      const processedQuestion = {
        ...questionData,
        questionType: questionData.questionType, // 保留原始questionType字段
        type: getTypeFromBackend(questionData.questionType),
        title: questionData.title || '',
        content: modifyQuestionContentImageSizeInHTML(questionData.content),
        answer: questionData.correctAnswer || questionData.answer,
        optionA: modifyQuestionContentImageSizeInHTML(options.A || ''),
        optionB: modifyQuestionContentImageSizeInHTML(options.B || ''),
        optionC: modifyQuestionContentImageSizeInHTML(options.C || ''),
        optionD: modifyQuestionContentImageSizeInHTML(options.D || ''),
        explanation: modifyQuestionContentImageSizeInHTML(questionData.explanation || '')
      };
      
      // 设置查看数据并显示查看对话框
      viewQuestionData.value = processedQuestion;
      showViewDialog.value = true;
      
      console.log('查看题目:', questionId);
    } else {
      ElMessage.error(response.message || '获取题目详情失败');
    }
  } catch (error) {
    console.error('获取题目详情失败:', error);
    ElMessage.error('获取题目详情失败');
  }
};

// 编辑题目
const editQuestion = async (question: any) => {
  // 检查题目对象的有效性
  if (!question) {
    ElMessage.error('题目对象无效');
    return;
  }

  // 获取题目ID，优先使用 questionId，其次使用 id
  const questionId = question.questionId || question.id;

  // 检查ID的有效性
  if (!questionId || isNaN(Number(questionId))) {
    ElMessage.error('题目ID无效，无法编辑');
    console.error('无效的题目ID:', questionId);
    return;
  }

  try {
    // 先重置表单，确保没有旧数据
    resetForm();
    
    // 确保传递给API的ID是数字类型
    const numericQuestionId = Number(questionId);
    const response: any = await props.apiModule.getQuestion(numericQuestionId);
    if (response.code === 200) {
      const questionData = response.data;
      
      // 处理选项数据
      let options: Record<string, string> = {};
      if (questionData.options && typeof questionData.options === 'string') {
        try {
          options = JSON.parse(questionData.options);
        } catch (e) {
          console.error('解析选项数据失败:', e);
        }
      }
      
      // 设置表单数据
      Object.assign(questionForm, {
        id: numericQuestionId, // 使用处理后的 questionId
        title: questionData.title || '',
        content: modifyQuestionContentImageSizeInHTML(questionData.content),
        type: getTypeFromBackend(questionData.questionType),
        difficulty: questionData.difficulty,
        category: getCategoryCode(questionData.category || ''), // 将中文分类转换为代码
        subCategory: getSubCategoryCode(questionData.category || '', questionData.subCategory || ''), // 将中文子分类转换为代码
        explanation: modifyQuestionContentImageSizeInHTML(questionData.explanation || ''),
        answer: questionData.correctAnswer || questionData.answer,
        optionA: modifyQuestionContentImageSizeInHTML(options.A || ''),
        optionB: modifyQuestionContentImageSizeInHTML(options.B || ''),
        optionC: modifyQuestionContentImageSizeInHTML(options.C || ''),
        optionD: modifyQuestionContentImageSizeInHTML(options.D || '')
      });
      
      // 处理多选题答案
      if (questionForm.type === 'multiple_choice' && typeof questionForm.answer === 'string') {
        questionForm.answer = questionForm.answer.split(',');
      }
      
      // 设置为编辑模式
      isEdit.value = true;
      
      // 显示对话框
      showAddDialog.value = true;
      
      // 在下一个事件循环中更新编辑器内容，确保DOM已更新
      setTimeout(() => {
        // 更新主内容编辑器
        if (editorRef.value && questionForm.content) {
          editorRef.value.setHtml(questionForm.content);
        } else if (editorRef.value) {
          editorRef.value.setHtml('');
        }
        
        // 更新选项编辑器
        if (optionAEditorRef.value && questionForm.optionA) {
          optionAEditorRef.value.setHtml(questionForm.optionA);
        } else if (optionAEditorRef.value) {
          optionAEditorRef.value.setHtml('');
        }
        if (optionBEditorRef.value && questionForm.optionB) {
          optionBEditorRef.value.setHtml(questionForm.optionB);
        } else if (optionBEditorRef.value) {
          optionBEditorRef.value.setHtml('');
        }
        if (optionCEditorRef.value && questionForm.optionC) {
          optionCEditorRef.value.setHtml(questionForm.optionC);
        } else if (optionCEditorRef.value) {
          optionCEditorRef.value.setHtml('');
        }
        if (optionDEditorRef.value && questionForm.optionD) {
          optionDEditorRef.value.setHtml(questionForm.optionD);
        } else if (optionDEditorRef.value) {
          optionDEditorRef.value.setHtml('');
        }
        
        // 更新解析编辑器
        if (explanationEditorRef.value && questionForm.explanation) {
          explanationEditorRef.value.setHtml(questionForm.explanation);
        } else if (explanationEditorRef.value) {
          explanationEditorRef.value.setHtml('');
        }
      }, 0);
      
      console.log('编辑题目:', questionId, '表单数据已设置');
    } else {
      ElMessage.error(response.message || '获取题目详情失败');
    }
  } catch (error) {
    console.error('获取题目详情失败:', error);
    ElMessage.error('获取题目详情失败');
  }
};



// 后端题型转前端题型
const getTypeFromBackend = (backendType: string) => {
  // 现在前后端使用相同的题型值，直接返回
  return backendType;
};

// 保存题目
const saveQuestion = async () => {
  if (!questionFormRef.value) return;

  await questionFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return;

    // 如果是编辑模式，检查ID的有效性
    if (isEdit.value) {
      if (!questionForm.id || isNaN(questionForm.id)) {
        ElMessage.error('题目ID无效，无法更新');
        return;
      }
    }

    // 前端题型转后端题型
    const getBackendType = (frontendType: string) => {
      // 现在前后端使用相同的题型值，直接返回
      return frontendType;
    };
    
    // 获取分类和子分类的中文名称
    const categoryText = getCategoryText(questionForm.category);
    const subCategoryText = getSubCategoryText(questionForm.category, questionForm.subCategory);
    
    // 准备表单数据
    const formData: Record<string, any> = {
      questionType: getBackendType(questionForm.type),
      title: questionForm.title,
      content: questionForm.content,
      correctAnswer: questionForm.answer,
      category: categoryText, // 使用中文分类名称
      subCategory: subCategoryText, // 使用中文子分类名称
      difficulty: questionForm.difficulty,
      explanation: questionForm.explanation || ''
    };

    // 处理选项
    if (questionForm.type === 'single_choice' || questionForm.type === 'multiple_choice') {
      formData.options = JSON.stringify({
        A: questionForm.optionA,
        B: questionForm.optionB,
        C: questionForm.optionC,
        D: questionForm.optionD
      });
    } else if (questionForm.type === 'fill_blank' || questionForm.type === 'true_false') {
      // 填空题和判断题也需要设置空的options，避免数据库约束错误
      formData.options = JSON.stringify({});
    }

    // 处理多选题答案 - 确保答案格式正确
    if (questionForm.type === 'multiple_choice' && Array.isArray(questionForm.answer)) {
      formData.correctAnswer = questionForm.answer.join(',');
    }

    try {
      let response;
      console.log('保存题目:', isEdit.value ? '编辑模式' : '添加模式', formData);
      
      if (isEdit.value) {
        response = await props.apiModule.updateQuestion(questionForm.id, formData);
      } else {
        response = await props.apiModule.addQuestion(formData);
      }

      if ((response as any).code === 200) {
        ElMessage.success(isEdit.value ? '更新成功' : '添加成功');
        // 先关闭对话框
        showAddDialog.value = false;
        // 然后重置表单
        resetForm();
        // 最后刷新列表
        fetchQuestionList();
      } else {
        ElMessage.error(response.message || (isEdit.value ? '更新失败' : '添加失败'));
      }
    } catch (error) {
      console.error('保存题目失败:', error);
      ElMessage.error(isEdit.value ? '更新失败' : '添加失败');
    }
  });
};

// 删除题目
const deleteQuestion = async (question: any) => {
  // 检查题目对象的有效性
  if (!question) {
    ElMessage.error('题目对象无效');
    return;
  }

  // 获取题目ID，优先使用 questionId，其次使用 id
  const questionId = question.questionId || question.id;

  // 检查ID的有效性
  if (!questionId || isNaN(Number(questionId))) {
    ElMessage.error('题目ID无效，无法删除');
    console.error('无效的题目ID:', questionId);
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除这道题目吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const response: any = await props.apiModule.deleteQuestion(questionId);
    if (response.code === 200) {
      ElMessage.success('删除成功');
      fetchQuestionList();
    } else {
      ElMessage.error(response.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 处理多选变化
const handleSelectionChange = (selection: any[]) => {
  selectedQuestions.value = selection;
};

// 批量删除题目
const handleBatchDelete = async () => {
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning('请选择要删除的题目');
    return;
  }

  // 检查所选题目的ID有效性
  const ids = selectedQuestions.value.map(question => question.questionId || question.id);
  const invalidIds = ids.filter(id => !id || isNaN(Number(id)));
  
  if (invalidIds.length > 0) {
    ElMessage.error('存在无效的题目ID，无法进行批量删除');
    console.error('无效的题目ID列表:', invalidIds);
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedQuestions.value.length} 道题目吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const response: any = await props.apiModule.batchDeleteQuestions(ids);
    if (response.code === 200) {
      ElMessage.success(`成功删除 ${selectedQuestions.value.length} 道题目`);
      selectedQuestions.value = [];
      fetchQuestionList();
    } else {
      ElMessage.error(response.message || '批量删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }
};

// 题型改变处理
const handleTypeChange = (type: string) => {
  questionForm.answer = type === 'multiple_choice' ? [] : '';
  // 如果切换到非选择题，清空选项
  if (type !== 'single_choice' && type !== 'multiple_choice') {
    questionForm.optionA = '';
    questionForm.optionB = '';
    questionForm.optionC = '';
    questionForm.optionD = '';
  }
};

// 分类改变处理
const handleCategoryChange = (category: string) => {
  // 清空子分类选择
  questionForm.subCategory = '';
};

// 重置表单
const resetForm = () => {
  // 先重置表单数据
  Object.assign(questionForm, {
    id: null,
    title: '',
    content: '',
    type: '', // 默认题型为空
    difficulty: 'easy',
    category: '', // 重置分类字段
    subCategory: '', // 重置子分类字段
    optionA: '',
    optionB: '',
    optionC: '',
    optionD: '',
    answer: '',
    explanation: '',
    options: '' // 清空options字段
  });
  
  // 重置表单验证
  if (questionFormRef.value) {
    questionFormRef.value.resetFields();
  }
  // 重置编辑状态
  isEdit.value = false;
  
  // 清空编辑器内容
  setTimeout(() => {
    if (editorRef.value) {
      editorRef.value.setHtml('');
    }
    if (optionAEditorRef.value) {
      optionAEditorRef.value.setHtml('');
    }
    if (optionBEditorRef.value) {
      optionBEditorRef.value.setHtml('');
    }
    if (optionCEditorRef.value) {
      optionCEditorRef.value.setHtml('');
    }
    if (optionDEditorRef.value) {
      optionDEditorRef.value.setHtml('');
    }
    if (explanationEditorRef.value) {
      explanationEditorRef.value.setHtml('');
    }
  }, 0);
  
  // 注意：不再在这里销毁编辑器实例，避免添加和编辑题目时的交叉错误
  // 编辑器实例将在组件卸载时统一销毁
};

// 对话框关闭处理
const handleDialogClose = () => {
  // 只重置表单数据，不销毁编辑器实例
  resetForm();
  showAddDialog.value = false;
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchQuestionList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchQuestionList();
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-';
  return new Date(dateString).toLocaleString('zh-CN');
};

// 获取题型标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    single_choice: 'primary',
    multiple_choice: 'success',
    true_false: 'warning',
    fill_blank: 'info'
  };
  return typeMap[type] || 'primary';
};

// 获取题型文本
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    single_choice: '单选题',
    multiple_choice: '多选题',
    true_false: '判断题',
    fill_blank: '填空题'
  };
  return typeMap[type] || type;
};

// 获取难度标签类型
const getDifficultyTagType = (difficulty: string) => {
  const difficultyMap: Record<string, string> = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  };
  return difficultyMap[difficulty] || 'warning';
};

// 获取难度文本
const getDifficultyText = (difficulty: string) => {
  const difficultyMap: Record<string, string> = {
    easy: '简单',
    medium: '中等',
    hard: '困难',
    'Easy': '简单',
    'Medium': '中等',
    'Hard': '困难'
  };
  return difficultyMap[difficulty] || difficulty;
};

// 获取模块文本
const getModuleText = (module: string) => {
  switch (module) {
    case 'politics':
      return '时政';
    case 'commonSense':
      return '常识';
    case 'language':
      return '言语理解';
    case 'judgment':
      return '判断';
    case 'quantitative':
      return '数量';
    case 'dataAnalysis':
      return '资料分析';
    default:
      return '未知';
  }
};

// 获取分类文本
const getCategoryText = (category: string) => {
  // 定义分类的文本映射
  const categoryTextMap: Record<string, string> = {
    // 常识模块分类
    Politics: '政治',
    Economics: '经济',
    HistoryLiterature: '文史',
    ScienceLife: '科学与生活',
    Geography: '地理',
    Law: '法律',
    ManagementDocuments: '管理与公文',
    // 言语模块分类
    SegRead: '片段阅读',
    SenExp: '语句表达',
    LogFill: '逻辑填空',
    // 数量模块分类
    MulCha: '倍数特性',
    EquPro: '方程问题',
    AriGeoSeq: '等差数列和等比数列',
    PerPro: '周期问题',
    EngPro: '工程问题',
    GeoPro: '几何问题',
    IncExcPro: '容斥原理问题',
    ExtValPro: '最值问题',
    AgePro: '年龄问题',
    SolPro: '溶液问题',
    PlanEquPro: '植树与方程问题',
    EcoPro: '经济利润问题',
    TraPro: '行程问题',
    ComPermPro: '排列组合问题',
    EasyNumPro: '数量易拿分小题型',
    // 判断模块分类
    DefRea: '定义判断',
    AnaRea: '类比推理',
    LogRea: '逻辑判断',
    GraRea: '图形推理',
    // 资料模块分类
    FastCal: '八大常用速算技巧',
    BaseVal: '基期量',
    CurrVal: '现期量',
    GrowthRt: '增长率',
    GrowthAmt: '增长量',
    IntvGrowth: '间隔增长率',
    ProdGrowth: '乘积增长率',
    AnnGrowth: '年均增长率',
    MixGrowth: '混合增长率',
    Proportion: '比重',
    Average: '平均数',
    Multiple: '倍数',
    ANotA: 'A与非A思想',
    CompAnaly: '综合分析'
  };

  // 返回分类的文本，如果找不到则返回原始值
  return categoryTextMap[category] || category;
};

// 获取分类代码（从中文到英文代码的映射）
const getCategoryCode = (categoryText: string) => {
  // 定义分类的反向映射
  const categoryCodeMap: Record<string, string> = {
    // 常识模块分类
    '政治': 'Politics',
    '经济': 'Economics',
    '文史': 'HistoryLiterature',
    '科学与生活': 'ScienceLife',
    '地理': 'Geography',
    '法律': 'Law',
    '管理与公文': 'ManagementDocuments',
    // 言语模块分类
    '片段阅读': 'SegRead',
    '语句表达': 'SenExp',
    '逻辑填空': 'LogFill',
    // 数量模块分类
    '倍数特性': 'MulCha',
    '方程问题': 'EquPro',
    '等差数列和等比数列': 'AriGeoSeq',
    '周期问题': 'PerPro',
    '工程问题': 'EngPro',
    '几何问题': 'GeoPro',
    '容斥原理问题': 'IncExcPro',
    '最值问题': 'ExtValPro',
    '年龄问题': 'AgePro',
    '溶液问题': 'SolPro',
    '植树与方程问题': 'PlanEquPro',
    '经济利润问题': 'EcoPro',
    '行程问题': 'TraPro',
    '排列组合问题': 'ComPermPro',
    '数量易拿分小题型': 'EasyNumPro',
    // 判断模块分类
    '定义判断': 'DefRea',
    '类比推理': 'AnaRea',
    '逻辑判断': 'LogRea',
    '图形推理': 'GraRea',
    // 资料模块分类
    '八大常用速算技巧': 'FastCal',
    '基期量': 'BaseVal',
    '现期量': 'CurrVal',
    '增长率': 'GrowthRt',
    '增长量': 'GrowthAmt',
    '间隔增长率': 'IntvGrowth',
    '乘积增长率': 'ProdGrowth',
    '年均增长率': 'AnnGrowth',
    '混合增长率': 'MixGrowth',
    '比重': 'Proportion',
    '平均数': 'Average',
    '倍数': 'Multiple',
    'A与非A思想': 'ANotA',
    '综合分析': 'CompAnaly'
  };

  // 返回分类的代码，如果找不到则返回原始值
  return categoryCodeMap[categoryText] || categoryText;
};


// 格式化答案显示
const formatAnswer = (answer: any, type: string) => {
  if (type === 'true_false') {
    return answer === 'true' || answer === true ? '正确' : '错误';
  }
  if (type === 'multiple_choice') {
    if (Array.isArray(answer)) {
      return answer.join(', ');
    }
    if (typeof answer === 'string' && answer.includes(',')) {
      return answer.split(',').join(', ');
    }
    return answer;
  }
  return answer;
};

// 获取子分类文本
const getSubCategoryText = (category: string, subCategory: string) => {
  // 定义子分类的文本映射
  const subCategoryTextMap: Record<string, Record<string, string>> = {
    // 常识模块子分类
    Politics: {
      CurrentPolitics: '时事政治',
      PolicyInterpretation: '政策解读',
      PoliticalTheory: '政治理论'
    },
    Economics: {
      MacroEconomics: '宏观经济',
      MicroEconomics: '微观经济',
      EconomicPolicy: '经济政策'
    },
    HistoryLiterature: {
      ChineseHistory: '中国历史',
      WorldHistory: '世界历史',
      LiteraryKnowledge: '文学常识'
    },
    ScienceLife: {
      NaturalScience: '自然科学',
      LifeCommonSense: '生活常识',
      TechnologyFrontier: '科技前沿'
    },
    Geography: {
      PhysicalGeography: '自然地理',
      HumanGeography: '人文地理',
      GeographicalKnowledge: '地理常识'
    },
    Law: {
      ConstitutionalLaw: '宪法法律',
      AdministrativeLaw: '行政法',
      CivilLaw: '民法'
    },
    ManagementDocuments: {
      Management: '管理学',
      OfficialDocumentWriting: '公文写作',
      AdministrativeManagement: '行政管理'
    },
    // 言语模块子分类
    SegRead: {
      CentralComprehension: '中心理解题',
      DetailJudgment: '细节判断题'
    },
    SenExp: {
      DiscourseSelection: '接语选择题',
      SentenceFilling: '语句填空题',
      SentenceOrdering: '语句排序题'
    },
    LogFill: {
      WordAnalysis: '词的辨析',
      ContextualAnalysis: '语境分析'
    },
    // 数量模块子分类
    MulCha: {
      Parity: '奇偶性',
      Divisibility: '整除特性',
      RatioMultiple: '比例倍数'
    },
    EquPro: {
      LinearEquation: '一元一次方程',
      BinaryLinearEquation: '二元一次方程',
      IndeterminateEquation: '不定方程'
    },
    // 判断模块子分类
    DefRea: {
      DefinitionReasoning: '定义推理',
      ConceptAnalysis: '概念分析'
    },
    AnaRea: {
      AnalogyReasoning: '类比推理',
      RelationshipAnalysis: '关系分析'
    },
    LogRea: {
      LogicalReasoning: '逻辑推理',
      PropositionalLogic: '命题逻辑'
    },
    GraRea: {
      GraphicReasoning: '图形推理',
      PatternRecognition: '模式识别'
    },
    // 资料模块子分类
    FastCal: {
      QuickCalculation: '快速计算',
      Estimation: '估算技巧'
    },
    BaseVal: {
      BasePeriod: '基期计算',
      BaseGrowth: '基期增长'
    },
    CurrVal: {
      CurrentPeriod: '现期计算',
      CurrentGrowth: '现期增长'
    },
    GrowthRt: {
      GrowthRate: '增长率计算',
      YearOnYear: '同比计算'
    },
    GrowthAmt: {
      GrowthAmount: '增长量计算',
      AbsoluteChange: '绝对变化'
    },
    IntvGrowth: {
      IntervalGrowth: '间隔增长率',
      MultiPeriod: '多期计算'
    },
    ProdGrowth: {
      ProductGrowth: '乘积增长率',
      CompoundGrowth: '复合增长率'
    },
    AnnGrowth: {
      AnnualGrowth: '年均增长率',
      AverageGrowth: '平均增长率'
    },
    MixGrowth: {
      MixedGrowth: '混合增长率',
      CompositeGrowth: '综合增长率'
    },
    Proportion: {
      Weight: '权重计算',
      Share: '份额计算'
    },
    Average: {
      Mean: '平均数计算',
      WeightedAverage: '加权平均'
    },
    Multiple: {
      Ratio: '倍数计算',
      Proportionality: '比例关系'
    },
    ANotA: {
      Complement: '补集思想',
      Difference: '差集思想'
    },
    CompAnaly: {
      Comprehensive: '综合分析',
      DataInterpretation: '数据解读'
    }
  };

  // 返回子分类的文本，如果找不到则返回原始值
  return subCategoryTextMap[category]?.[subCategory] || subCategory;
};

// 获取子分类代码（从中文到英文代码的映射）
const getSubCategoryCode = (category: string, subCategoryText: string) => {
  // 定义子分类的反向映射
  const subCategoryCodeMap: Record<string, Record<string, string>> = {
    // 常识模块子分类
    Politics: {
      '时事政治': 'CurrentPolitics',
      '政策解读': 'PolicyInterpretation',
      '政治理论': 'PoliticalTheory'
    },
    Economics: {
      '宏观经济': 'MacroEconomics',
      '微观经济': 'MicroEconomics',
      '经济政策': 'EconomicPolicy'
    },
    HistoryLiterature: {
      '中国历史': 'ChineseHistory',
      '世界历史': 'WorldHistory',
      '文学常识': 'LiteraryKnowledge'
    },
    ScienceLife: {
      '自然科学': 'NaturalScience',
      '生活常识': 'LifeCommonSense',
      '科技前沿': 'TechnologyFrontier'
    },
    Geography: {
      '自然地理': 'PhysicalGeography',
      '人文地理': 'HumanGeography',
      '地理常识': 'GeographicalKnowledge'
    },
    Law: {
      '宪法法律': 'ConstitutionalLaw',
      '行政法': 'AdministrativeLaw',
      '民法': 'CivilLaw'
    },
    ManagementDocuments: {
      '管理学': 'Management',
      '公文写作': 'OfficialDocumentWriting',
      '行政管理': 'AdministrativeManagement'
    },
    // 言语模块子分类
    SegRead: {
      '中心理解题': 'CentralComprehension',
      '细节判断题': 'DetailJudgment'
    },
    SenExp: {
      '接语选择题': 'DiscourseSelection',
      '语句填空题': 'SentenceFilling',
      '语句排序题': 'SentenceOrdering'
    },
    LogFill: {
      '词的辨析': 'WordAnalysis',
      '语境分析': 'ContextualAnalysis'
    },
    // 数量模块子分类
    MulCha: {
      '奇偶性': 'Parity',
      '整除特性': 'Divisibility',
      '比例倍数': 'RatioMultiple'
    },
    EquPro: {
      '一元一次方程': 'LinearEquation',
      '二元一次方程': 'BinaryLinearEquation',
      '不定方程': 'IndeterminateEquation'
    },
    // 判断模块子分类
    DefRea: {
      '定义推理': 'DefinitionReasoning',
      '概念分析': 'ConceptAnalysis'
    },
    AnaRea: {
      '类比推理': 'AnalogyReasoning',
      '关系分析': 'RelationshipAnalysis'
    },
    LogRea: {
      '逻辑推理': 'LogicalReasoning',
      '命题逻辑': 'PropositionalLogic'
    },
    GraRea: {
      '图形推理': 'GraphicReasoning',
      '模式识别': 'PatternRecognition'
    },
    // 资料模块子分类
    FastCal: {
      '快速计算': 'QuickCalculation',
      '估算技巧': 'Estimation'
    },
    BaseVal: {
      '基期计算': 'BasePeriod',
      '基期增长': 'BaseGrowth'
    },
    CurrVal: {
      '现期计算': 'CurrentPeriod',
      '现期增长': 'CurrentGrowth'
    },
    GrowthRt: {
      '增长率计算': 'GrowthRate',
      '同比计算': 'YearOnYear'
    },
    GrowthAmt: {
      '增长量计算': 'GrowthAmount',
      '绝对变化': 'AbsoluteChange'
    },
    IntvGrowth: {
      '间隔增长率': 'IntervalGrowth',
      '多期计算': 'MultiPeriod'
    },
    ProdGrowth: {
      '乘积增长率': 'ProductGrowth',
      '复合增长率': 'CompoundGrowth'
    },
    AnnGrowth: {
      '年均增长率': 'AnnualGrowth',
      '平均增长率': 'AverageGrowth'
    },
    MixGrowth: {
      '混合增长率': 'MixedGrowth',
      '综合增长率': 'CompositeGrowth'
    },
    Proportion: {
      '权重计算': 'Weight',
      '份额计算': 'Share'
    },
    Average: {
      '平均数计算': 'Mean',
      '加权平均': 'WeightedAverage'
    },
    Multiple: {
      '倍数计算': 'Ratio',
      '比例关系': 'Proportionality'
    },
    ANotA: {
      '补集思想': 'Complement',
      '差集思想': 'Difference'
    },
    CompAnaly: {
      '综合分析': 'Comprehensive',
      '数据解读': 'DataInterpretation'
    }
  };

  // 返回子分类的代码，如果找不到则返回原始值
  // 首先找到category对应的映射表，然后在其中查找subCategoryText
  const categoryMap = subCategoryCodeMap[category];
  if (categoryMap) {
    // 遍历categoryMap找到对应的value
    for (const [code, text] of Object.entries(categoryMap)) {
      if (text === subCategoryText) {
        return code;
      }
    }
  }
  return subCategoryText;
};

// 监听apiModule变化
watch(
  () => props.apiModule,
  (newApiModule) => {
    if (newApiModule && newApiModule.getQuestions) {
      console.log('API模块已准备好，获取题目列表');
      fetchQuestionList();
    }
  },
  { immediate: true }
);

// 处理添加题目点击事件
const handleAddQuestionClick = () => {
  // 重置表单数据
  resetForm();
  // 确保不是编辑模式
  isEdit.value = false;
  // 显示添加对话框
  showAddDialog.value = true;
};

// 手动批量导入功能
const validateManualImportFormat = () => {
  try {
    const content = manualImportContent.value.trim();
    if (!content) {
      ElMessage.warning('请输入题目内容');
      isFormatValid.value = false;
      return;
    }

    // 按照示例格式解析内容
    const questions = parseManualQuestions(content);
    if (questions.length > 0) {
      parsedQuestions.value = questions;
      isFormatValid.value = true;
      ElMessage.success(`格式正确，共识别到 ${questions.length} 道题目`);
    } else {
      isFormatValid.value = false;
      ElMessage.error('未识别到有效题目格式');
    }
  } catch (error) {
    isFormatValid.value = false;
    ElMessage.error('格式验证失败: ' + (error as Error).message);
  }
};

// 解析手动输入的题目内容
const parseManualQuestions = (content: string) => {
  const questions: any[] = [];
  // 按照示例格式解析
  // 使用【例 X】作为题目分隔符
  const questionBlocks = content.split(/【例\s*\d+】/).filter(block => block.trim());
  
  for (const block of questionBlocks) {
    const trimmedBlock = block.trim();
    if (!trimmedBlock) continue;
    
    // 直接提取题目内容（从开始到第一个选项之前的部分）
    let questionContent = '';
    // 查找第一个选项的位置 (A. B. C. D.)
    const firstOptionMatches = [...trimmedBlock.matchAll(/([A-D])\./g)];
    if (firstOptionMatches.length > 0) {
      const firstOptionIndex = firstOptionMatches[0].index || 0;
      questionContent = trimmedBlock.substring(0, firstOptionIndex).trim();
    } else {
      // 如果没有找到选项，使用整个块作为内容
      questionContent = trimmedBlock;
    }
    
    // 移除题目编号部分（如【例 1】）
    const contentWithoutNumber = questionContent.replace(/【例\s*\d+】/, '').trim();
    
    // 移除来源信息（括号内容）
    let finalContent = contentWithoutNumber.replace(/\([^)]*\)/, '').trim();
    
    // 保持原有的<p>标签结构，但确保格式正确
    // 如果内容中已经包含<p>标签，则保持原样
    if (finalContent.includes('<p>')) {
      // 确保<p>标签正确闭合
      if (!finalContent.startsWith('<p>')) {
        finalContent = '<p>' + finalContent;
      }
      if (!finalContent.endsWith('</p>')) {
        finalContent = finalContent + '</p>';
      }
      // 修复可能的标签问题
      finalContent = finalContent.replace(/<p>(\s*)<p>/g, '<p>').replace(/<\/p>(\s*)<\/p>/g, '</p>');
    } else {
      // 如果没有<p>标签，按照原来的逻辑处理
      finalContent = finalContent.replace(/\n/g, '<br>');
    }
    
    // 根据文本内容预处理规范，移除多余空白字符
    finalContent = finalContent.replace(/\s+/g, ' ');
    
    // 提取选项
    const options: Record<string, string> = {};
    const optionPattern = /([A-D])\.\s*([^\n]*?)(?=\n[A-D]\.|\s*[A-D]、|\s*正确答案：|$)/gs;
    const optionMatches = [...trimmedBlock.matchAll(optionPattern)];
    for (const match of optionMatches) {
      options[match[1]] = match[2].trim();
    }
    
    // 提取正确答案
    const answerMatch = trimmedBlock.match(/正确答案：\s*([A-D])/);
    const answer = answerMatch ? answerMatch[1] : '';
    
    // 提取解析（如果存在）
    const explanationMatch = trimmedBlock.match(/解析：\s*(.*?)(?=【例\s*\d+】|$)/s);
    const explanation = explanationMatch ? explanationMatch[1].trim() : '';
    
    questions.push({
      content: finalContent,
      options,
      answer,
      explanation,
      source: '', // 不提取来源信息
      type: 'single_choice', // 默认为单选题
      difficulty: 'medium' // 默认难度
    });
  }
  
  return questions;
};

// 执行手动批量导入
const executeManualImport = async () => {
  if (!isFormatValid.value || parsedQuestions.value.length === 0) {
    ElMessage.warning('请先验证格式或没有可导入的题目');
    return;
  }

  // 获取对应的API模块
  let targetApiModule = props.apiModule;
  if (manualImportModuleType.value && manualImportModuleType.value !== props.moduleType) {
    // 这里需要根据选择的模块类型获取对应的API模块
    // 由于我们无法直接访问其他模块的API，这里保持使用当前模块的API
    // 在实际应用中，您可能需要通过某种方式获取对应模块的API
    console.warn('手动导入模块类型与当前模块不匹配，使用当前模块API');
  }

  try {
    let successCount = 0;
    for (const question of parsedQuestions.value) {
      // 获取分类和子分类的中文名称
      const categoryText = getCategoryText(manualImportCategory.value || '');
      const subCategoryText = getSubCategoryText(manualImportCategory.value || '', manualImportSubCategory.value || '');
      
      // 准备题目数据
      const questionData = {
        content: question.content,
        questionType: 'single_choice',
        difficulty: question.difficulty,
        options: JSON.stringify(question.options),
        correctAnswer: question.answer,
        explanation: question.explanation || '',
        category: categoryText, // 使用中文大分类
        subCategory: subCategoryText // 使用中文小分类
      };

      try {
        const response = await targetApiModule.addQuestion(questionData);
        if (response.code === 200) {
          successCount++;
        }
      } catch (error) {
        console.error('导入单个题目失败:', error);
      }
    }

    ElMessage.success(`成功导入 ${successCount} 道题目`);
    showManualImportDialog.value = false;
    manualImportContent.value = '';
    manualImportModuleType.value = ''; // 重置模块类型
    manualImportCategory.value = ''; // 重置大分类
    manualImportSubCategory.value = ''; // 重置小分类
    isFormatValid.value = false;
    parsedQuestions.value = [];
    // 刷新题目列表
    fetchQuestionList();
  } catch (error) {
    ElMessage.error('批量导入失败: ' + (error as Error).message);
  }
};

// 重置手动导入
const resetManualImport = () => {
  manualImportContent.value = '';
  manualImportModuleType.value = ''; // 重置模块类型
  manualImportCategory.value = ''; // 重置大分类
  manualImportSubCategory.value = ''; // 重置小分类
  isFormatValid.value = false;
  parsedQuestions.value = [];
  if (manualImportContentInputTimer) {
    clearTimeout(manualImportContentInputTimer);
  }
};

// 处理手动导入模块选择变化
const handleManualImportModuleChange = (moduleType: string) => {
  // 重置分类字段
  manualImportCategory.value = '';
  manualImportSubCategory.value = '';
};

// 处理手动导入大分类变化
const handleManualImportCategoryChange = (category: string) => {
  // 重置小分类字段
  manualImportSubCategory.value = '';
};

// 手动输入内容变化时的处理
const onManualContentInput = () => {
  // 添加防抖，避免频繁验证
  if (manualImportContentInputTimer) {
    clearTimeout(manualImportContentInputTimer);
  }
  manualImportContentInputTimer = setTimeout(() => {
    if (manualImportContent.value.trim()) {
      validateManualImportFormatSilently();
    }
  }, 500);
};

// 静默验证格式（不显示消息提示）
const validateManualImportFormatSilently = () => {
  try {
    const content = manualImportContent.value.trim();
    if (!content) {
      isFormatValid.value = false;
      parsedQuestions.value = [];
      return;
    }

    // 按照示例格式解析内容
    const questions = parseManualQuestions(content);
    if (questions.length > 0) {
      parsedQuestions.value = questions;
      isFormatValid.value = true;
    } else {
      isFormatValid.value = false;
      parsedQuestions.value = [];
    }
  } catch (error) {
    isFormatValid.value = false;
    parsedQuestions.value = [];
  }
};

// 获取截断后的题目内容（只显示前10个字并隐藏图片）
const getTruncatedContent = (content: string) => {
  if (!content) return '-';
  
  // 移除HTML标签获取纯文本
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = content;
  const textContent = tempDiv.textContent || tempDiv.innerText || '';
  
  // 截取前10个字
  const truncatedText = textContent.length > 10 ? textContent.substring(0, 10) + '...' : textContent;
  
  // 返回处理后的文本，不包含图片
  return truncatedText;
};

// 组件挂载时获取数据
onMounted(() => {
  // 确保apiModule已经准备好再获取数据
  if (props.apiModule && props.apiModule.getQuestions) {
    fetchQuestionList();
  } else {
    console.log('组件挂载时API模块未准备好，等待watch触发');
  }
});

// 组件销毁时清理编辑器
onBeforeUnmount(() => {
  // 获取所有可能的编辑器实例
  const editors = [
    editorRef.value,
    optionAEditorRef.value,
    optionBEditorRef.value,
    optionCEditorRef.value,
    optionDEditorRef.value,
    explanationEditorRef.value
  ];
  
  // 销毁编辑器实例
  destroyEditors(editors);
  
  // 重置编辑器引用
  resetEditorRefs([editorRef, optionAEditorRef, optionBEditorRef, optionCEditorRef, optionDEditorRef, explanationEditorRef]);
  
  // 清理定时器
  if (manualImportContentInputTimer) {
    clearTimeout(manualImportContentInputTimer);
  }
});

// 公共方法：打开手动导入对话框
const openManualImportDialog = () => {
  showManualImportDialog.value = true;
};

// 暴露给父组件的方法
defineExpose({
  openManualImportDialog
});
</script>

<style scoped>
.question-bank-management {
  padding: 20px;
}

/* 确保所有通过v-html渲染的内容中的图片都能等比例缩放 */
:deep([v-html]) img {
  max-width: 100%;
  height: auto !important;
  width: auto !important;
  object-fit: contain;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header {
  margin-bottom: 20px;
  
  .header-top {
    margin-bottom: 15px;
    
    h1 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }
  }

  .header-buttons {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;

    .excel-uploader {
      margin-right: 10px;
    }
  }

  :deep(.template-help-dialog) {
    .el-message-box__content {
      max-height: 70vh;
      overflow-y: auto;
    }

    .template-help {
      h3 {
        margin-top: 0;
        color: #409EFF;
      }

      h4 {
        color: #67C23A;
        margin-top: 20px;
        margin-bottom: 10px;
      }

      ol, ul {
        padding-left: 20px;
        margin: 10px 0;
      }

      li {
        margin: 5px 0;
      }

      strong {
        color: #E6A23C;
      }
    }
  }
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.question-content {
  line-height: 1.5;
  word-break: break-word;

  img {
    max-width: 100%;
    max-height: 200px;
    object-fit: contain;
    margin: 10px 0;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

.question-detail {
  .detail-item {
    margin-bottom: 15px;
    
    label {
      font-weight: bold;
      color: #333;
      margin-bottom: 5px;
      display: inline-block;
      min-width: 80px;
    }
    
    .content {
      margin-top: 5px;
      line-height: 1.6;
      color: #666;
    }
    
    .options {
      margin-top: 5px;
      
      div {
        margin-bottom: 5px;
        padding: 5px 0;
        color: #666;
      }
    }
    
    .answer {
      color: #e6a23c;
      font-weight: bold;
    }
  }
}

/* 富文本编辑器样式 */
:deep(.w-e-text-container) {
  line-height: 1.5 !important;
}

:deep(.w-e-text-placeholder) {
  color: #c0c4cc;
  font-style: normal;
}

:deep(.w-e-toolbar) {
  border-bottom: 1px solid #e4e7ed;
}

:deep(.w-e-text) {
  min-height: 100px;
}

:deep(.w-e-text img) {
  max-width: 100%;
  max-height: 180px;
  width: auto;
  height: auto;
  object-fit: contain;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 查看详情中的富文本内容样式 */
.question-detail .content {
  img {
    max-width: 100%;
    max-height: 180px;
    width: auto;
    height: auto;
    object-fit: contain;
    border-radius: 4px;
    margin: 5px 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  p {
    margin: 8px 0;
    line-height: 1.6;
  }
}

.question-detail .options {
  img {
    max-width: 100%;
    max-height: 140px;
    width: auto;
    height: auto;
    object-fit: contain;
    display: block;
    margin: 10px 0;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  span {
    display: inline-block;
    vertical-align: top;
  }
}

/* 弹出框样式 */
:deep(.option-popover), :deep(.explanation-popover) {
  max-width: 90vw;
  
  .el-popover__title {
    font-weight: bold;
    color: #409EFF;
  }
  
  .option-content, .explanation-content {
    max-height: 60vh;
    overflow-y: auto;
    padding: 10px;
    
    img {
      max-width: 100%;
      height: auto;
      object-fit: contain;
      border-radius: 4px;
      margin: 10px 0;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    
    p {
      margin: 8px 0;
      line-height: 1.6;
    }
  }
}

.explanation-preview {
  cursor: pointer;
  max-height: 100px;
  overflow: hidden;
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 40px;
    background: linear-gradient(transparent, rgba(255, 255, 255, 0.9));
    pointer-events: none;
  }
}
.question-view-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 25px;
    max-height: calc(80vh - 100px);
    overflow-y: auto;
    overflow-x: hidden;
    
    &::-webkit-scrollbar {
      width: 8px;
    }
    
    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 4px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #c0c4cc;
      border-radius: 4px;
    }
  }
  
  :deep(.el-dialog) {
    max-width: 95vw;
  }
}

.question-detail {
  .detail-item {
    margin-bottom: 24px;
    
    label {
      font-weight: 600;
      color: #333;
      margin-bottom: 12px;
      display: block;
      font-size: 16px;
    }
    
    .content {
      margin-top: 12px;
      line-height: 1.8;
      color: #333;
      font-size: 15px;
      background-color: #f8f9fa;
      padding: 16px;
      border-radius: 8px;
      max-width: 100%;
      overflow-x: hidden;
      word-break: break-word;
      
      :deep(img) {
        max-width: 100% !important;
        height: auto !important;
        max-height: 300px !important;
        object-fit: scale-down !important;
        object-position: center !important;
        border-radius: 8px !important;
        margin: 12px auto !important;
        display: block !important;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1) !important;
        
        @media screen and (max-width: 768px) {
          max-height: 180px !important;
        }
        
        @media screen and (max-width: 480px) {
          max-height: 120px !important;
        }
      }
      
      :deep(p) {
        margin: 12px 0;
        line-height: 1.8;
      }
    }
    
    .options {
      margin-top: 16px;
      
      div {
        margin-bottom: 12px;
        padding: 12px 16px;
        color: #333;
        background-color: #f8f9fa;
        border-radius: 8px;
        font-size: 15px;
        line-height: 1.6;
        
        :deep(img) {
          max-width: 100% !important;
          max-height: 180px !important;
          height: auto !important;
          object-fit: scale-down !important;
          object-position: center !important;
          display: block !important;
          margin: 12px auto !important;
          border-radius: 8px !important;
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1) !important;
          
          @media screen and (max-width: 768px) {
            max-height: 140px !important;
          }
          
          @media screen and (max-width: 480px) {
            max-height: 100px !important;
          }
        }
      }
    }
    
    .answer {
      color: #67c23a;
      font-weight: 600;
      font-size: 15px;
      margin-top: 8px;
      padding: 8px 12px;
      background-color: #f0f9eb;
      border-radius: 4px;
      display: inline-block;
    }
  }
}

/* 手动导入对话框样式 */
.manual-import-dialog {
  .el-textarea {
    margin-bottom: 15px;
  }
  
  .validation-result {
    margin-bottom: 15px;
    padding: 10px;
    border-radius: 4px;
    
    &.valid {
      background-color: #f0f9eb;
      border: 1px solid #e1f3d8;
      color: #67c23a;
    }
    
    &.invalid {
      background-color: #fef0f0;
      border: 1px solid #fbc4c4;
      color: #f56c6c;
    }
  }
  
  .question-preview {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px;
    margin-top: 15px;
    background-color: #f5f7fa;
    
    .question-item {
      padding: 10px;
      border-bottom: 1px solid #e4e7ed;
      
      &:last-child {
        border-bottom: none;
      }
      
      .question-content {
        font-weight: bold;
        margin-bottom: 5px;
      }
      
      .question-options {
        margin: 5px 0;
        
        .option-item {
          margin-left: 10px;
        }
      }
    }
  }
}
</style>